import store from '../modules/store'
import config from '../config'
import frd from '../modules/formatRequestData'
import tool from './tool'
import formatRequestData from '../modules/formatRequestData'
import ws from './ws'

let closeLoadingKey = false
let requesting = false

export default {
  config,
  store,
  updateWindowInfo() {
    let titleBarHeight = '45px'
    let navigateBarHeight = '170rpx'

    let re = wx.getSystemInfoSync()
    re = re.statusBarHeight
    store.setItem('windowInfo', {
      statusBarHeight: `${re}px`,
      titleBarHeight,
      navigateBarHeight,
      contentHeight: `calc(100vh - ${re}px - ${navigateBarHeight})`,
      contentHeightWithoutTitleBar: `calc(100vh - ${re}px - ${titleBarHeight} - ${navigateBarHeight})`,
    })
  },
  wait(n) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        return resolve()
      }, n * 1000);
    })
  },
  requestData(apiName = '', data = {}, method = 'post', showLoading = true) {
    let apiName_c = apiName
    return new Promise(async (resolve, reject) => {
      requesting = true
      let t
      if (showLoading && store.getItem('requestShowLoading')) {
        closeLoadingKey = false
        t = setTimeout(() => {
          wx.showLoading({
            title: '请稍候',
            mask: true
          })
        }, 0)
      }
      data = formatRequestData.formatBeforeSend(apiName, data)
      if (method == 'get') {
        apiName += this.qsStringify(data)
      }
      console.log('HTTPS - 开始', apiName)
      wx.request({
        url: config.serverURL + apiName,
        method,
        header: {
          ...await tool.execFunc(async () => {
            if (store.getItem('userData')) {
              return {
                token: store.getItem('userData_token')
              }
            }
            return {}
          })
        },
        data: (method == 'post' ? data : undefined),
        mask: true,
        fail(e) {
          if (showLoading) wx.hideLoading()
          console.log('请求失败：', e)
          resolve({
            status: 0,
            content: '请求失败（非后端返回）'
          })
        },
        async success(e) {
          clearTimeout(t)
          closeLoadingKey = true
          if (showLoading) wx.hideLoading()
          e.data = frd.format(apiName_c, e.data)
          console.log('HTTPS - 完成', apiName, e.data)
          if (e.data.status == -1) {
            store.removeItem('userData')
            store.removeItem('userData_token')
            await tool.wait(0.01)
            store.setItem('mainCurrentPageIndex', -1)
            await tool.wait(0.01)
            store.setItem('mainCurrentPageIndex', 0)
            wx.navigateBack({
              delta: 100
            })
            await tool.wait(0.5)
            tool.handleShowToast(`${e.data.content}`, 'none')
            return
          }
          resolve(e.data)
        }
      })
    })
  },
  qsStringify(data = {}) {
    let re = '?'
    for (let i = 0; i < Object.keys(data).length; i++) {
      let key = Object.keys(data)[i]
      let value = data[Object.keys(data)[i]]
      if (i) re += '&'
      re += `${key}=${value}`
    }
    return re
  },
  isLogined() {
    return store.getItem('userData') != undefined
  },
  async handleNotLogin() {
    wx.redirectTo({
      url: '/pages/login/login',
    })
  },
  getLoginCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        complete: async (res) => {
          return resolve(res.code)
        }
      });
    })
  },
  validatePhoneNumber(phone) {
    const regex = /^1[3-9]\d{9}$/;
    return regex.test(phone);
  },
  readFileToBase64(filePath) {
    const fs = wx.getFileSystemManager();
    return new Promise((resolve, reject) => {
      fs.readFile({
        filePath: filePath,
        encoding: 'base64',
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },
  uploadFileToServer(filePath, showLoading = true) {
    return new Promise(async (resolve, reject) => {
      if (showLoading) wx.showLoading({
        title: '正在上传',
        mask: true
      })
      wx.uploadFile({
        url: config.serverURL + '/file/upload',
        filePath: filePath,
        name: 'file',
        header: {
          token: (store.getItem('userData') ? store.getItem('userData').token : undefined)
        },
        success(res) {
          if (showLoading) wx.hideLoading()
          return resolve(res.data)
          console.log('上传成功', res);
        },
        fail(error) {
          wx.hideLoading()
          return resolve({
            status: 0,
            content: '上传失败'
          })
          console.error('上传失败', error);
        }
      });
    })
  },
  handleShowToast(title, icon = 'auto', time = 1000) {
    wx.showToast({
      title,
      icon: icon == 'auto' ? ((() => {
        if (title.indexOf('成功') + 1) return 'success'
        if (title.indexOf('失败') + 1) return 'error'
      })()) : icon,
      duration: time
    })
  },
  handleShowToastWithMask(title, icon = 'auto', time = 1000) {
    wx.showToast({
      title,
      icon: icon == 'auto' ? ((() => {
        if (title.indexOf('成功') + 1) return 'success'
        if (title.indexOf('失败') + 1) return 'error'
      })()) : icon,
      mask: true,
      duration: time
    })
  },
  async testConnection() {
    try {
      let re = await this.requestData('/test', {}, 'get')
      return re.data === true
    } catch (error) {
      return false
    }
  },
  handleShowModel(content = '', showCancel = true, okCallBack = () => {}, cancleCallBack = () => {}) {
    wx.showModal({
      content: content,
      mask: true,
      showCancel,
      complete: (res) => {
        if (res.cancel) {
          try {
            cancleCallBack()
          } catch (error) {

          }
        }

        if (res.confirm) {
          try {
            okCallBack()
          } catch (error) {

          }
        }
      }
    })
  },
  handleExitLogin() {
    for (let i = 0; i < 100; i++) wx.navigateBack()
    tool.redirectToIndex()
  },
  setPageData(_this) {
    _this.setData({
      ...store.getItem('windowInfo'),
      userData: store.getItem('userData'),
      logined: store.getItem('userData') !== undefined,
      isAdmin: (store.getItem('userData') !== undefined && store.getItem('userData').isAdmin),
      imagePrefix: config.imagePrefix,
      userData_openId: store.getItem('openId')
    })
  },
  controlInput(title = '请输入内容', tip = '请在下面的文本框内输入文字', type = 'singleText', defaultValue = null, callBack = () => {}, check = () => {}) {
    store.setItem('controlInput', {
      title,
      tip,
      type,
      check,
      callBack,
      defaultValue
    })
    wx.navigateTo({
      url: '/pages/inputValue/inputValue',
    })
  },
  controlPicker(title = '请输入内容', tip = '请在下面的文本框内输入文字', type = 'selector', defaultValue = null, options = [], callBack = () => {}, check = () => {}) {
    store.setItem('controlInput', {
      title,
      tip,
      type,
      check,
      callBack,
      defaultValue,
      options
    })
    wx.navigateTo({
      url: '/pages/inputValue/inputValue',
    })
  },
  controlSettingsPage(title = '', optionsOrInit = [], handleToBottom = () => {}) {
    store.setItem('controlSettingsPage', {
      title,
      options: (typeof (optionsOrInit) === 'object' ? optionsOrInit : undefined),
      init: (typeof (optionsOrInit) === 'function' ? optionsOrInit : undefined),
      handleToBottom
    })
    wx.navigateTo({
      url: '/pages/settings/settings',
    })
  },
  formatTimeNew(inputTime = new Date()) {
    function getPeriod(hours) {
      if (hours >= 0 && hours < 6) {
        return '凌晨';
      } else if (hours >= 6 && hours < 11) {
        return '上午';
      } else if (hours >= 11 && hours < 14) {
        return '中午';
      } else if (hours >= 14 && hours < 18) {
        return '下午';
      } else {
        return '晚上';
      }
    }

    function getWeekName(n) {
      switch (n) {
        case 0:
          return '星期天'
        case 1:
          return '星期一'
        case 2:
          return '星期二'
        case 3:
          return '星期三'
        case 4:
          return '星期四'
        case 5:
          return '星期五'
        case 6:
          return '星期六'
      }
    }
    let currentTime = new Date()
    let oneDaySecond = 86400000
    let currentDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000)
    let lastDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 - oneDaySecond)
    let nextDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond)
    let nextDayEnd = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond * 2)
    let prefix = ''
    if (inputTime >= currentDayStart && inputTime < nextDayStart) {
      prefix = '今天'
    }
    if (inputTime >= lastDayStart && inputTime < currentDayStart) {
      prefix = '昨天'
    }
    if (inputTime >= nextDayStart && inputTime < nextDayEnd) {
      prefix = '明天'
    }
    if (prefix == '') {
      prefix = (inputTime.getFullYear() == currentTime.getFullYear() ? '' : inputTime.getFullYear().toString() +
        '年') + (inputTime.getMonth() + 1).toString() + '月' + inputTime.getDate() + '日 '
    }
    prefix += getPeriod(inputTime.getHours()) + ' '
    prefix += inputTime.getHours().toString() + ':'
    if (inputTime.getMinutes() < 10) {
      prefix += '0'
    }
    prefix += inputTime.getMinutes().toString() + ' '
    prefix += getWeekName(inputTime.getDay())
    return prefix
  },
  compressImage(filePath, quality = 30, maxWidth = 512, maxHeight = 512) {
    return new Promise((resolve, reject) => {
      wx.compressImage({
        src: filePath, // 原始图片路径
        quality: quality, // 压缩质量
        height: maxHeight, // 最大高度
        width: maxWidth, // 最大宽度
        success(res) {
          resolve(res.tempFilePath); // 返回压缩后的图片路径
        },
        fail(err) {
          reject(err); // 如果压缩失败，则返回错误信息
        }
      });
    });
  },
  chooseImage(count = 1) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: count, // 选择图片的数量，最多可以选择的数量
        sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
        sourceType: ['album', 'camera'], // 可以选择相册或拍照
        success(res) {
          resolve(res.tempFilePaths); // 返回选择的图片路径数组
        },
        fail(err) {
          // reject(); // 如果选择图片失败，返回错误信息
        }
      });
    });
  },
  dcJSON(obj) {
    return JSON.parse(JSON.stringify(obj))
  },
  async execFunc(func = () => {}, args = []) {
    return await func(...args)
  },
  formatDateTime(date) {
    date = new Date(date)
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始的
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },
  controlRichTextEditor(title = '', defaultValue = '', callBack = async () => {}) {
    store.setItem('richTextPage', {
      title,
      defaultValue
    })
    store.setItem('richTextEditorCallBack', callBack)
    wx.navigateTo({
      url: '/pages/richTextEditor/richTextEditor',
    })
  },
  controlColorEditor(r, g, b, callBack = () => {}) {
    tool.controlSettingsPage('编辑颜色', (handleReloadColorEditorPage) => {
      return [{
          list: [{
            title: '预览',
            right: {
              type: 'colorPreview',
              value: `rgb(${r},${g},${b})`
            },
            disabled: true
          }]
        },
        {
          title: '分量',
          list: [{
              title: '红',
              right: {
                type: 'text',
                value: r
              },
              callBack: () => {
                tool.controlInput('编辑红色', '', 'number', r, (value, done) => {
                  r = value
                  done()
                  handleReloadColorEditorPage()
                }, (value) => {
                  value = parseInt(value)
                  if (isNaN(value)) throw new Error('红色值应为不小于0且不大于255的整数')
                  if (value < 0 || value > 255) {
                    throw new Error('红色值应为不小于0且不大于255的整数')
                  }
                })
              }
            },
            {
              title: '绿',
              right: {
                type: 'text',
                value: g
              },
              callBack: () => {
                tool.controlInput('编辑绿色', '', 'number', g, (value, done) => {
                  g = value
                  done()
                  handleReloadColorEditorPage()
                }, (value) => {
                  value = parseInt(value)
                  if (isNaN(value)) throw new Error('绿色值应为不小于0且不大于255的整数')
                  if (value < 0 || value > 255) {
                    throw new Error('绿色值应为不小于0且不大于255的整数')
                  }
                })
              }
            },
            {
              title: '蓝',
              right: {
                type: 'text',
                value: b
              },
              callBack: () => {
                tool.controlInput('编辑蓝色', '', 'number', b, (value, done) => {
                  b = value
                  done()
                  handleReloadColorEditorPage()
                }, (value) => {
                  value = parseInt(value)
                  if (isNaN(value)) throw new Error('蓝色值应为不小于0且不大于255的整数')
                  if (value < 0 || value > 255) {
                    throw new Error('蓝色值应为不小于0且不大于255的整数')
                  }
                })
              }
            }
          ]
        },
        {
          title: '操作',
          list: [{
            title: '保存',
            icon: '保存',
            callBack: async () => {
              try {
                callBack(r, g, b)
                wx.navigateBack()
              } catch (error) {
                console.log(error)
              }
            }
          }]
        }
      ]
    })
  },
  async flow(main = async () => {}, handleError = async () => {}) {
    const te = (str) => {
      throw str
    }
    try {
      await main(te)
    } catch (error) {
      await handleError(error.toString())
    }
  },
  async login() {
    let loginCode = await tool.getLoginCode()
    if (!loginCode) throw '无法获取LoginCode'
    let re_login = await tool.requestData('/user/login', {
      code: loginCode
    })
    if (re_login.status) {
      wx.setStorageSync('showLogo', false)
      store.setItem('userData', re_login.data)
      store.setItem('userData_token', re_login.data.token)
    } else {
      if (wx.getStorageSync('showLogo') === '') {
        wx.setStorageSync('showLogo', true)
      }
      store.removeItem('userData')
      store.removeItem('userData_token')
    }
    return re_login.data
  },
  handleSelect(title = '', arr = [], field = undefined, callBack = () => {}) {
    tool.controlSettingsPage(title, async () => {
      let re1 = []
      for (let i = 0; i < arr.length; i++) {
        re1.push({
          title: field === undefined ? arr[i] : arr[i][field],
          callBack: () => {
            try {
              callBack(arr[i])
            } catch (error) {

            }
          }
        })
      }
      return [{
        list: re1
      }]
    })
  },
  check: {
    phone(str = '') {
      return str.match(/1[0-9]{10}/) != null
    },
    password(password) {
      const regex = /^[a-zA-Z0-9_]{8,16}$/;
      return regex.test(password);
    }
  },
  debounce(func, delay = 300) {
    let timer;
    return function (...args) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(this, args);
      }, delay);
    };
  },
  async getUserOpenId() {
    let re = await tool.requestData('/user/getOpenId', {
      code: await tool.getLoginCode()
    }, 'get')
    if (re.status == 1) {
      return re.data
    } else {
      throw re.content
    }
  },
  async getUserData() {
    return store.getItem('userData')
  },
  page: {
    getSearchPatrolForm(callBack = () => {}) {
      let form = {}
      const handleSaveConditions = (o) => {
        form = Object.assign(form, o)
      }
      tool.controlSettingsPage('设置巡查查询条件', async (refreshPage_conditions) => {
        return [{
            title: '基本条件',
            list: [{
                title: '巡查ID',
                right: {
                  type: 'text',
                  value: !form.id ? '' : `#${form.id}`
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              id: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑巡查ID',
                    '',
                    'singleText',
                    form.id,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            id: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && isNaN(Number(value))) throw '必须为数字';
                      }
                  );
                }
              },
              {
                title: '创建时间开始',
                right: {
                  type: 'text',
                  value: form.createdStart
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              createdStart: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑创建时间开始',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.createdStart,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            createdStart: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '创建时间结束',
                right: {
                  type: 'text',
                  value: form.createdEnd
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              createdEnd: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑创建时间结束',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.createdEnd,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            createdEnd: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '描述',
                right: {
                  type: 'text',
                  value: form.patrolDesc
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              patrolDesc: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑描述',
                    '',
                    'singleText',
                    form.patrolDesc,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            patrolDesc: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '图片个数',
                right: {
                  type: 'text',
                  value: form.imageCount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              imageCount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑图片个数',
                    '0-5',
                    'singleText',
                    form.imageCount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            imageCount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && (isNaN(Number(value)) || Number(value) < 0 || Number(value) > 5)) throw '图片个数必须在0到5之间';
                      }
                  );
                }
              },
              {
                title: '有无位置',
                right: {
                  type: 'text',
                  value: form.hasLocation ? '有' : '无'
                },
                callBack: async (e) => {
                  tool.handleShowActionSheet([{
                      name: '有',
                      callBack: () => tool.flow(async () => {
                        await handleSaveConditions({
                          hasLocation: 1
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    },
                    {
                      name: '无',
                      callBack: () => tool.flow(async () => {
                        await handleSaveConditions({
                          hasLocation: 0
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    }
                  ]);
                }
              },
              {
                title: '校区',
                right: {
                  type: 'text',
                  value: form.campusName
                },
                callBack: async () => {
                  wx.showActionSheet({
                    itemList: ['清除', '选择'],
                    success: async (e) => {
                      if (e.tapIndex === 0) {
                        await handleSaveConditions({
                          campusId: undefined,
                          campusName: undefined
                        });
                        refreshPage_conditions();
                        tool.handleShowToastWithMask('成功');
                        await tool.wait(0.5);
                      }
                      if (e.tapIndex === 1) {
                        tool.select.campus(async (e) => {
                          await handleSaveConditions({
                            campusId: e.id,
                            campusName: e.name
                          });
                          refreshPage_conditions();
                          tool.handleShowToastWithMask('成功');
                          await tool.wait(0.5);
                        })
                      }
                    }
                  })

                }
              },
              {
                title: '类别',
                right: {
                  type: 'text',
                  value: form.categoryName
                },
                callBack: async (e) => {
                  wx.showActionSheet({
                    itemList: ['清除', '选择'],
                    success: async (e) => {
                      if (e.tapIndex === 0) {
                        await handleSaveConditions({
                          categoryId: undefined,
                          categoryName: undefined
                        });
                        refreshPage_conditions();
                        tool.handleShowToastWithMask('成功');
                        await tool.wait(0.5);
                      }
                      if (e.tapIndex === 1) {
                        tool.select.category(async (e) => {
                          await handleSaveConditions({
                            categoryId: e.id,
                            categoryName: e.name
                          });
                          refreshPage_conditions();
                          tool.handleShowToastWithMask('成功');
                          await tool.wait(0.5);
                        })
                      }
                    }
                  })

                }
              },
              {
                title: '状态',
                right: {
                  type: 'text',
                  value: (() => {
                    if (form.status === 1) return '等待'
                    if (form.status === 2) return '延期'
                    if (form.status === 3) return '满意度调查'
                    if (form.status === 4) return '完成'
                    if (form.status === 5) return '拒绝'
                  })()
                },
                callBack: async (e) => {
                  wx.showActionSheet({
                    itemList: ['不限', '等待', '延期', '满意度调查', '完成', '拒绝'],
                    success: async (e) => {
                      e = e.tapIndex
                      if (e === 0) {
                        await handleSaveConditions({
                          status: undefined
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                      if (e > 0) {
                        await handleSaveConditions({
                          status: e
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                    }
                  })
                }
              },
              {
                title: '结束时间开始',
                right: {
                  type: 'text',
                  value: form.endTimeStart
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              endTimeStart: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑结束时间开始',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.endTimeStart,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            endTimeStart: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        console.log(value)
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '结束时间结束',
                right: {
                  type: 'text',
                  value: form.endTimeEnd
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              endTimeEnd: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑结束时间结束',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.endTimeEnd,

                    [], async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            endTimeEnd: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '延期次数',
                right: {
                  type: 'text',
                  value: form.delayCount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              delayCount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑延期次数',
                    '',
                    'singleText',
                    form.delayCount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            delayCount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && (isNaN(Number(value)) || Number(value) < 0))
                          throw '必须为非负数';
                      }
                  );
                }
              },
              {
                title: '延期人',
                right: {
                  type: 'text',
                  value: form.delayUserName
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              delayUserId: undefined,
                              delayUserName: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.page.userSearch(['选择一个用户'], async (e) => {
                    e = e[0]
                    console.log(e)
                    await handleSaveConditions({
                      delayUserId: e.id,
                      delayUserName: e.username
                    });
                    tool.handleShowToast('成功');
                    refreshPage_conditions();
                    wx.navigateBack({
                      delta: 2
                    })
                  }, false, false)
                }
              },
            ]
          },
          {
            title: '评价条件',
            list: [{
                title: '评价时间开始',
                right: {
                  type: 'text',
                  value: form.feedbackCreatedStart
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              feedbackCreatedStart: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑评价时间开始',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.feedbackCreatedStart,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            feedbackCreatedStart: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '评价时间结束',
                right: {
                  type: 'text',
                  value: form.feedbackCreatedEnd
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              feedbackCreatedEnd: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑评价时间结束',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.feedbackCreatedEnd,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            feedbackCreatedEnd: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '评价描述',
                right: {
                  type: 'text',
                  value: form.feedbackDesc
                },
                callBack: async (e) => {
                  tool.controlInput(
                    '编辑评价描述',
                    '',
                    'singleText',
                    form.feedbackDesc,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            feedbackDesc: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '评价分数',
                right: {
                  type: 'text',
                  value: (() => {
                    if (form.feedbackRating === 1) return '非常满意'
                    if (form.feedbackRating === 2) return '满意'
                    if (form.feedbackRating === 3) return '一般'
                    if (form.feedbackRating === 4) return '不满意'
                    if (form.feedbackRating === 5) return '非常不满意'
                  })()
                },
                callBack: async (e) => {
                  wx.showActionSheet({
                    itemList: ['不限', '非常满意', '满意', '一般', '不满意', '非常不满意'],
                    success: async (e) => {
                      e = e.tapIndex
                      if (!e) {
                        await handleSaveConditions({
                          feedbackRating: undefined
                        });
                        tool.handleShowToast('成功');
                        await tool.wait(0.5);
                        refreshPage_conditions();
                        return
                      }
                      await handleSaveConditions({
                        feedbackRating: e
                      });
                      tool.handleShowToast('成功');
                      await tool.wait(0.5);
                      refreshPage_conditions();
                    }
                  })
                }
              },
              {
                title: '评价次数',
                right: {
                  type: 'text',
                  value: form.feedbackCount
                },
                callBack: async (e) => {
                  tool.controlInput(
                    '编辑评价次数',
                    '',
                    'number',
                    form.feedbackCount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            feedbackCount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && (isNaN(Number(value)) || Number(value) < 0))
                          throw '必须为非负数字';
                      }
                  );
                }
              },
            ]
          },
          {
            title: '处理条件',
            list: [{
                title: '处理时间开始',
                right: {
                  type: 'text',
                  value: form.handleCreatedStart
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handleCreatedStart: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑处理时间开始',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.handleCreatedStart,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handleCreatedStart: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '处理时间结束',
                right: {
                  type: 'text',
                  value: form.handleCreatedEnd
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handleCreatedEnd: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑处理时间结束',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.handleCreatedEnd,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handleCreatedEnd: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );

                }
              },
              {
                title: '处理描述',
                right: {
                  type: 'text',
                  value: form.handleDesc
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handleDesc: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑处理描述',
                    '',
                    'singleText',
                    form.handleDesc,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handleDesc: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '处理图片数量',
                right: {
                  type: 'text',
                  value: form.handleImageCount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handleImageCount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑处理图片数量',
                    '0-5',
                    'number',
                    form.handleImageCount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handleImageCount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && (isNaN(Number(value)) || Number(value) < 0 || Number(value) > 5))
                          throw '必须在0到5之间';
                      }
                  );
                }
              },
              {
                title: '处理次数',
                right: {
                  type: 'text',
                  value: form.handleCount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handleCount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑处理次数',
                    '',
                    'number',
                    form.handleCount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handleCount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && (isNaN(Number(value)) || Number(value) < 0))
                          throw '必须为非负数字';
                      }
                  );
                }
              },
              {
                title: '是否拒绝处理',
                right: {
                  type: 'text',
                  value: form.handleReject ? '是' : '否'
                },
                callBack: async (e) => {
                  tool.handleShowActionSheet([{
                      name: '是',
                      callBack: () => tool.flow(async () => {
                        await handleSaveConditions({
                          handleReject: 1
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    },
                    {
                      name: '否',
                      callBack: () => tool.flow(async () => {
                        await handleSaveConditions({
                          handleReject: 0
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    }
                  ]);
                }
              },
            ]
          },
          {
            title: '驳回条件',
            list: [{
                title: '驳回时间开始',
                right: {
                  type: 'text',
                  value: form.rejectTimeStart
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              rejectTimeStart: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑驳回时间开始',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.rejectTimeStart,
                    [],
                    async (value, done) => {
                        if (await new Promise(async (resolve, reject) => {
                            wx.showActionSheet({
                              itemList: ['清除', '输入'],
                              success: async (e) => {
                                e = e.tapIndex
                                if (e === 0) {
                                  await handleSaveConditions({
                                    rejectTimeStart: undefined
                                  });
                                  tool.handleShowToast('成功');
                                  refreshPage_conditions();
                                  resolve(true)
                                }
                                if (e === 1) {
                                  resolve(false)
                                }
                              },
                              fail() {
                                resolve(true)
                              }
                            })
                          })) return
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            rejectTimeStart: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '驳回时间结束',
                right: {
                  type: 'text',
                  value: form.rejectTimeEnd
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              rejectTimeEnd: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlPicker(
                    '编辑驳回时间结束',
                    '格式：YYYY-MM-DD HH:MM:SS',
                    'dateTime',
                    form.rejectTimeEnd,
                    [],
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            rejectTimeEnd: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value.indexOf('null') + 1) throw '选择日期时间'
                        if (value.indexOf('undefined') + 1) throw '选择日期时间'
                      }
                  );
                }
              },
              {
                title: '驳回描述',
                right: {
                  type: 'text',
                  value: form.rejectDesc
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              rejectDesc: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑驳回描述',
                    '',
                    'singleText',
                    form.rejectDesc,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            rejectDesc: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '驳回次数',
                right: {
                  type: 'text',
                  value: form.rejectCount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              rejectCount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑驳回次数',
                    '',
                    'number',
                    form.rejectCount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            rejectCount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && (isNaN(Number(value)) || Number(value) < 0))
                          throw '必须为非负数字';
                      }
                  );
                }
              },
            ]
          },
          {
            title: '巡查人条件',
            list: [{
                title: '巡查人用户名',
                right: {
                  type: 'text',
                  value: form.patrolUsername
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              patrolUsername: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑巡查人用户名',
                    '',
                    'singleText',
                    form.patrolUsername,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            patrolUsername: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '巡查人手机号',
                right: {
                  type: 'text',
                  value: form.patrolPhone
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              patrolPhone: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑巡查人手机号',
                    '',
                    'singleText',
                    form.patrolPhone,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            patrolPhone: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && !tool.check.phone(value)) throw '请输入正确的手机号';
                      }
                  );
                }
              },
              {
                title: '巡查人账号',
                right: {
                  type: 'text',
                  value: form.patrolAccount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              patrolAccount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑巡查人账号',
                    '',
                    'singleText',
                    form.patrolAccount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            patrolAccount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '巡查人所属部门',
                right: {
                  type: 'text',
                  value: form.patrolDepartmentName
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              patrolDepartmentId: undefined,
                              patrolDepartmentName: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.select.department(async (e) => {
                    await handleSaveConditions({
                      patrolDepartmentId: e.id,
                      patrolDepartmentName: e.name
                    });
                    tool.handleShowToast('成功');
                    refreshPage_conditions();
                  })
                }
              },
              {
                title: '巡查人角色',
                right: {
                  type: 'text',
                  value: form.patrolRole
                },
                callBack: async (e) => {
                  wx.showActionSheet({
                    itemList: ['不限', '老师', '学生'],
                    success: async (e) => {
                      e = e.tapIndex
                      if (e === 0) {
                        await handleSaveConditions({
                          patrolRole: undefined
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                      if (e > 0) {
                        await handleSaveConditions({
                          patrolRole: e == 1 ? '老师' : '学生'
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                    }
                  })
                }
              },
            ]
          },
          {
            title: '负责人条件',
            list: [{
                title: '负责人用户名',
                right: {
                  type: 'text',
                  value: form.handlerUsername
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handlerUsername: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑负责人用户名',
                    '',
                    'singleText',
                    form.handlerUsername,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handlerUsername: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '负责人手机号',
                right: {
                  type: 'text',
                  value: form.handlerPhone
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handlerPhone: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑负责人手机号',
                    '',
                    'singleText',
                    form.handlerPhone,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handlerPhone: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && !tool.check.phone(value)) throw '请输入正确的手机号';
                      }
                  );
                }
              },
              {
                title: '负责人账号',
                right: {
                  type: 'text',
                  value: form.handlerAccount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handlerAccount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑负责人账号',
                    '',
                    'singleText',
                    form.handlerAccount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            handlerAccount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '负责人所属部门',
                right: {
                  type: 'text',
                  value: form.handlerDepartmentName
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              handlerDepartmentId: undefined,
                              handlerDepartmentName: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.select.department(async (e) => {
                    await handleSaveConditions({
                      handlerDepartmentId: e.id,
                      handlerDepartmentName: e.name
                    });
                    tool.handleShowToast('成功');
                    refreshPage_conditions();
                  })
                }
              },
              {
                title: '负责人角色',
                right: {
                  type: 'text',
                  value: form.handlerRole
                },
                callBack: async (e) => {
                  wx.showActionSheet({
                    itemList: ['不限', '老师', '学生'],
                    success: async (e) => {
                      e = e.tapIndex
                      if (e === 0) {
                        await handleSaveConditions({
                          handlerRole: undefined
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                      if (e > 0) {
                        await handleSaveConditions({
                          handlerRole: e == 1 ? '老师' : '学生'
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                    }
                  })
                }
              },
            ]
          },
          {
            title: '审核人条件',
            list: [{
                title: '审核人用户名',
                right: {
                  type: 'text',
                  value: form.reviewerUsername
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              reviewerUsername: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑审核人用户名',
                    '',
                    'singleText',
                    form.reviewerUsername,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            reviewerUsername: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '审核人手机号',
                right: {
                  type: 'text',
                  value: form.reviewerPhone
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              reviewerPhone: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑审核人手机号',
                    '',
                    'singleText',
                    form.reviewerPhone,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            reviewerPhone: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {
                        if (value && !tool.check.phone(value)) throw '请输入正确的手机号';
                      }
                  );
                }
              },
              {
                title: '审核人账号',
                right: {
                  type: 'text',
                  value: form.reviewerAccount
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              reviewerAccount: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.controlInput(
                    '编辑审核人账号',
                    '',
                    'singleText',
                    form.reviewerAccount,
                    async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveConditions({
                            reviewerAccount: value
                          });
                          tool.handleShowToast('成功');
                          await tool.wait(0.5);
                          done();
                          refreshPage_conditions();
                        }, err => tool.handleShowToast(`${err}`, 'error'));
                      },
                      (value) => {}
                  );
                }
              },
              {
                title: '审核人所属部门',
                right: {
                  type: 'text',
                  value: form.reviewerDepartmentName
                },
                callBack: async (e) => {
                  if (await new Promise(async (resolve, reject) => {
                      wx.showActionSheet({
                        itemList: ['清除', '输入'],
                        success: async (e) => {
                          e = e.tapIndex
                          if (e === 0) {
                            await handleSaveConditions({
                              reviewerDepartmentId: undefined,
                              reviewerDepartmentName: undefined
                            });
                            tool.handleShowToast('成功');
                            refreshPage_conditions();
                            resolve(true)
                          }
                          if (e === 1) {
                            resolve(false)
                          }
                        },
                        fail() {
                          resolve(true)
                        }
                      })
                    })) return
                  tool.select.department(async (e) => {
                    await handleSaveConditions({
                      reviewerDepartmentId: e.id,
                      reviewerDepartmentName: e.name
                    });
                    tool.handleShowToast('成功');
                    refreshPage_conditions();
                  })
                }
              },
              {
                title: '审核人角色',
                right: {
                  type: 'text',
                  value: form.reviewerRole
                },
                callBack: async (e) => {
                  wx.showActionSheet({
                    itemList: ['不限', '老师', '学生'],
                    success: async (e) => {
                      e = e.tapIndex
                      if (e === 0) {
                        await handleSaveConditions({
                          reviewerRole: undefined
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                      if (e > 0) {
                        await handleSaveConditions({
                          reviewerRole: e == 1 ? '老师' : '学生'
                        });
                        tool.handleShowToast('成功');
                        refreshPage_conditions();
                      }
                    }
                  })
                }
              },
            ]
          },
          {
            title: '操作',
            list: [{
              title: '确定',
              callBack: () => {
                let f = tool.dcJSON(form)
                let re = []
                for (let i = 0; i < Object.keys(f).length; i++) {
                  if (f[Object.keys(f)[i]] === '' || f[Object.keys(f)[i]] === undefined || f[Object.keys(f)[i]] === null) re.push(Object.keys(f)[i])
                }
                for (let i = 0; i < re.length; i++) delete f[re[i]]
                tool.postFrontStatus(`生成巡查查询表单 ${JSON.stringify(f)}`)
                try {
                  callBack(f)
                } catch (error) {

                }
              }
            }]
          }
        ];
      })
    },
    editForm(title = '', form = {
      field1: {
        name: '字段1',
        type: 'singleText'
      }
    }, value = {
      field: '字段1的值'
    }, okCallBack = (e) => {}, changeCallBack = (e) => {}) {
      tool.controlSettingsPage(title, async (reloadEditFormPage) => {
        let sett = []
        for (let i = 0; i < Object.keys(value).length; i++) {
          let k = Object.keys(value)[i]
          let v = value[k]
          sett.push({
            title: form[k] ? form[k].name : k,
            right: {
              type: 'text',
              value: v
            },
            callBack: () => {
              let type = (() => {
                if (!form[k]) return 'singleText'
                if (form[k].type instanceof Array) {
                  return 'multipleSelector'
                }
                return form[k].type
              })()
              let isSelect = (() => {
                if (type == 'singleText') return false
                if (type == 'multipleText') return false
                if (type == 'number') return false
                return true
              })()
              if (isSelect) {
                tool.controlPicker(`${form[k] ? form[k].name : k}`, '', type, v, (form[k].type instanceof Array) ? form[k].type : [], (val, done) => {
                  value[k] = val
                  try {
                    changeCallBack(value)
                  } catch (error) {

                  }
                  done()
                }, form[k] ? form[k].check : () => {})
              } else {
                tool.controlInput(`${form[k] ? form[k].name : k}`, '', type, v, (val, done) => {
                  value[k] = val
                  try {
                    changeCallBack(value)
                  } catch (error) {

                  }
                  done()
                }, form[k] ? form[k].check : () => {})
              }
            }
          })
        }
        return [{
            list: sett
          },
          {
            title: '操作',
            list: [{
              title: '确定',
              callBack: () => {
                wx.navigateBack()
                try {
                  okCallBack(value)
                } catch (error) {

                }
              }
            }]
          }
        ]
      })
    },
    async editUserData() {
      if (tool.isLogined() === false) {
        tool.handleShowToast('未登录', 'error')
        return
      }
      let userData = store.getItem('userData')
      const handleUpdateInfo = async (obj) => {
        let re = await tool.requestData('/user/updateInfo', obj)
        if (re.status == 1) {
          tool.postFrontStatus(`修改了个人信息 ${JSON.stringify(obj)}`)
          userData = Object.assign(tool.dcJSON(userData), obj)
          store.setItem('userData', userData)
        } else {
          throw re.content
        }
      }
      tool.postFrontStatus(`打开编辑个人资料界面`)
      tool.controlSettingsPage('编辑个人资料', async (reloadEditUserDataPage) => {
        let sett = [

          {
            title: '用户名',
            right: {
              type: 'text',
              value: userData.username
            },
            callBack: (e) => {
              tool.controlInput('用户名', '', 'singleText', userData.username, async (v, d) => {
                await tool.flow(async () => {
                  await handleUpdateInfo({
                    username: v
                  })
                  tool.handleShowToastWithMask('成功')
                  await tool.wait(0.5)
                  d()
                  reloadEditUserDataPage()
                  await tool.handleReloadIndex()
                }, (err) => {
                  tool.handleShowToast(err, 'error')
                })
              }, (v) => {
                if (!v || v.length > 16) throw '用户名不能为空且长度不能大于16'
              })
            }
          },

          {
            title: '管理员',
            right: {
              type: 'text',
              value: userData.isAdmin ? (userData.isAdmin === 1 ? '是' : '是（超级管理员）') : '否'
            },
            disabled: true
          },

          {
            title: '账号（学号/工号）',
            right: {
              type: 'text',
              value: userData.account
            },
            callBack: (e) => {
              tool.controlInput('账号（学号/工号）', '', 'singleText', userData.account, async (v, d) => {
                await tool.flow(async () => {
                  await handleUpdateInfo({
                    account: v
                  })
                  tool.handleShowToastWithMask('成功')
                  await tool.wait(0.5)
                  d()
                  reloadEditUserDataPage()
                  await tool.handleReloadIndex()
                }, (err) => {
                  tool.handleShowToast(err, 'error')
                })
              }, (v) => {
                if (!v || v.length > 16) throw '用户名不能为空且长度不能大于16'
              })
            }
          },

          // {
          //   title: '角色',
          //   right: {
          //     type: 'text',
          //     value: userData.role
          //   },
          //   callBack: async (e) => {
          //     let re = await tool.requestData('/setting/get', {
          //       key: 'role'
          //     }, 'get')
          //     if (re.status == 1) {
          //       tool.handleSelect('选择角色', re.data, undefined, async (item) => {
          //         await tool.flow(async () => {
          //           await handleUpdateInfo({
          //             role: item
          //           })
          //           tool.handleShowToastWithMask('成功')
          //           await tool.wait(0.5)
          //           wx.navigateBack()
          //           reloadEditUserDataPage()
          //           await tool.handleReloadIndex()
          //         }, (err) => {
          //           tool.handleShowToast(err, 'error')
          //         })
          //       })
          //     } else {
          //       tool.handleShowToast(re.content, 'error')
          //     }
          //   }
          // },

          {
            title: '手机号',
            right: {
              type: 'text',
              value: userData.phone
            },
            callBack: async (e) => {
              tool.controlInput('输入新的手机号', '', 'singleText', '', async (v1, d1) => {
                tool.handleShowModel('是否获取手机验证码并修改手机号？', true, async () => {
                  let re0 = await tool.requestData('/user/getVCode', {
                    phone: v1
                  }, 'get')
                  if (re0.status) {
                    tool.controlInput('输入验证码', `验证码已发送至${v1}`, 'singleText', '', async (v, d) => {
                      let re = await tool.requestData('/user/updateInfo', {
                        phone: v1,
                        vcode: v
                      })
                      if (re.status) {
                        tool.handleShowToastWithMask('成功')
                        await tool.wait(0.5)
                        wx.navigateBack({
                          delta: 2
                        })
                      } else {
                        tool.handleShowToast(re.content, 'error')
                      }
                    }, (v) => {
                      if (!v) throw '输入验证码'
                      if (v.length != 6) throw '输入6位验证码'
                    })
                    await tool.wait(0.3)
                    tool.handleShowToast('验证码已发送')
                  } else {
                    tool.handleShowToast(re0.content, 'error')
                  }
                })
              }, (v1) => {
                if (!tool.check.phone(v1)) throw '手机号有误'
              })

            }
          },

          {
            title: '部门',
            right: {
              type: 'text',
              value: userData.departmentInfo.name
            },
            callBack: async (e) => {

              let re = await tool.requestData('/user/getDepartmentList', {

              }, 'get')
              if (re.status == 1) {
                tool.handleSelect('选择部门', re.data, 'name', async (item) => {
                  await tool.flow(async () => {
                    await handleUpdateInfo({
                      departmentId: item.id,
                      departmentInfo: item
                    })
                    tool.handleShowToastWithMask('成功')
                    await tool.wait(0.5)
                    wx.navigateBack()
                    reloadEditUserDataPage()
                    await tool.handleReloadIndex()
                  }, (err) => {
                    tool.handleShowToast(err, 'error')
                  })
                })
              } else {
                tool.handleShowToast(re.content, 'error')
              }

            }
          },

        ]

        return [{
          list: sett
        }]
      })
    },
    changePassword() {
      tool.postFrontStatus(`打开修改密码界面`)
      tool.controlInput('输入新密码', '不短于8位且不长于16位', 'singleText', '', async (value1, done1) => {
        tool.controlInput('再次输入新密码', '不短于8位且不长于16位', 'singleText', '', async (value2, done2) => {
          let re = await tool.requestData('/user/updateInfo', {
            password: value1
          })
          if (re.status) {
            tool.handleShowToastWithMask('成功')
            await tool.wait(0.5)
            wx.navigateBack({
              delta: 2
            })
          } else {
            tool.handleShowToast(re.content, 'error')
          }
        }, (value) => {
          if (!value) throw '再次输入密码'
          if (value != value1) throw '两次输入的密码不一致'
        })
      }, (value) => {
        if (!value) throw '输入密码'
        if (!tool.check.password(value)) throw '输入密码'
      })
    },
    patrol: {
      async add() {
        const form = {
          "userId": (await tool.getUserData()).id,
          "desc": '',
          "image1": '',
          "image2": '',
          "image3": '',
          "image4": '',
          "image5": '',
          "location1": '',
          "location2": '',
          "campusId": null,
          "campusName": null,
          "categoryId": null,
          "categoryName": null,
          "status": 0,
          "endTime": tool.formatDateTime(tool.getNextWorkday(new Date(), tool.getHomeData().newPatrolDefaultWorkDays))
        }
        let showMoreOptions = true
        let imageList = []
        tool.controlFormPage('新建巡查', async (refreshPage) => {

          const tf = tool.formPageControls
          let re = tf.main(
            [
              tf.list.textarea('问题描述和具体位置', form.desc, (e) => {
                form.desc = e
              }),
              tf.list.imageSelector(imageList, false, 5, (list) => {
                imageList = list
                refreshPage()
              }, true),
              tf.list.buttonGroup('', [
                tf.list.button('位置', async () => {
                  const handleChoose = () => {
                    console.log(parseFloat(form.location1))
                    wx.chooseLocation({
                      latitude: parseFloat(form.location1),
                      longitude: parseFloat(form.location2),
                      success: (e) => {
                        if (e.errMsg == 'chooseLocation:ok') {
                          form.location1 = `${e.latitude}`
                          form.location2 = `${e.longitude}`
                          refreshPage()
                        } else {
                          tool.handleShowToast(e.errMsg)
                        }
                      },
                      fail: (e) => console.log(e)
                    })
                  }
                  if (form.location1 == '') {
                    handleChoose()
                  } else {
                    wx.showActionSheet({
                      itemList: ['预览', '清除'],
                      success: (ee) => {
                        ee = ee.tapIndex
                        if (ee === 0) {
                          handleChoose()
                        }
                        if (ee === 1) {
                          form.location1 = ''
                          form.location2 = ''
                          refreshPage()
                        }
                      }
                    })
                  }

                }, undefined, 'text', form.location1 == '' ? '可选' : `${form.location1},${form.location2}`),
                ...(() => {
                  if (showMoreOptions) {
                    return [
                      tf.list.button('校区', async () => {
                        let re = await tool.requestData('/campus/getList', {}, 'get')
                        if (re.status) {
                          tool.handleSelect('选择校区', re.data.default, 'name', (item) => {
                            form.campusId = item.id
                            form.campusName = item.name
                            refreshPage()
                            wx.navigateBack()
                          })
                        } else {
                          tool.handleShowToast(re.content, 'error')
                        }
                      }, undefined, 'text', form.campusName ? form.campusName : '请选择'),
                      tf.list.button('类别', async () => {
                        let re = await tool.requestData('/category/getList', {}, 'get')
                        if (re.status) {
                          tool.handleSelect('选择类别', re.data.default, 'name', (item) => {
                            form.categoryId = item.id
                            form.categoryName = item.name
                            refreshPage()
                            wx.navigateBack()
                          })
                        } else {
                          tool.handleShowToast(re.content, 'error')
                        }
                      }, undefined, 'text', form.categoryName ? form.categoryName : '请选择'),
                      tf.list.button('负责人处理截止时间', async () => {
                        tool.controlPicker('负责人处理截止时间', `默认时间为${tool.getHomeData()['newPatrolDefaultWorkDays']}个工作日之后`, 'dateTime', form.endTime, [], async (v, d) => {
                          form.endTime = v
                          refreshPage()
                          d()
                        }, async (v) => {
                          let re = await tool.requestData('/system/getServerTime', {}, 'get')
                          if (re.status) {
                            if (new Date(re.data) > new Date(v)) throw '负责人处理截止时间不能早于当前时间'
                          } else {
                            throw re.content
                          }
                        })
                      }, undefined, 'text', tool.formatTimeNew(new Date(form.endTime))),
                      // tf.list.button('显示简略选项', async () => {
                      //   showMoreOptions = false
                      //   refreshPage()
                      // }, undefined),
                    ]
                  } else {
                    return [
                      tf.list.button('显示更多选项', async () => {
                        showMoreOptions = true
                        refreshPage()
                      }, undefined),
                    ]
                  }
                })()

              ]),
            ],
            undefined,
            tool.formPageControls.bottom([
              tool.formPageControls.topBottom.button('提交', 'ok', async () => {

                tool.flow(async () => {
                  if (!form.desc) throw '输入描述'
                  if (form.desc.length > 256) throw '描述过长'
                  if (form.campusId === null) throw '选择校区'
                  if (form.categoryId === null) throw '选择类别'
                  if (form.desc.length > 128) throw `文字描述不能超过128个汉字`
                  if (imageList.length == 0) throw '添加图片'
                  const handleUploadImage = async (patrolId, list) => {
                    let res = []
                    for (let i = 0; i < list.length; i++) {
                      list[i] = await tool.compressImage(list[i])
                      let re = await tool.uploadFileToServer(list[i], false)
                      try {
                        re = JSON.parse(re)
                      } catch (error) {

                      }
                      res.push(re.data)
                    }
                    return res
                  }
                  wx.showLoading({
                    title: '正在创建巡查',
                  })
                  let re = await tool.requestData('/patrol/store', {
                    patrolData: form
                  }, 'post', false)
                  if (re.status) {
                    if (imageList.length) wx.showLoading({
                      title: '正在上传图片',
                    })
                    let images = await handleUploadImage(re.data, imageList)
                    wx.showLoading({
                      title: '正在发布',
                    })
                    let re_publish = await tool.requestData('/patrol/publish', {
                      id: re.data,
                      images
                    }, 'post', false)
                    if (re_publish.status) {
                      tool.postFrontStatus(`发布巡查 ${re.data}`)
                      store.setItem('addPatrol')
                      wx.hideLoading()
                      tool.handleShowToastWithMask('成功')
                      await tool.wait(0.5)
                      wx.navigateBack()
                      await tool.wait(0.5)
                      tool.page.patrol.info(re.data)
                    } else {
                      throw re_publish.content
                    }
                  } else {
                    throw re.content
                  }
                  wx.hideLoading()
                }, (err) => {
                  tool.handleShowToast(`${err}`, 'error')
                })
              }),
            ]))
          return re
        })
      },
      async info(patrolId) {
        let re = await tool.requestData('/patrol/singleDetail', {
          id: patrolId
        }, 'get')
        if (re.status) {

          let item = re.data

          if (!tool.store.getItem('useOldUI')) {
            tool.store.setItem('patrol_detail', {
              item
            })
            wx.navigateTo({
              url: '/pages/patrol_detail/patrol_detail',
            })
            return
          }

          let userData = store.getItem('userData')

          const handleUpdate = async () => {
            let re = await tool.requestData('/patrol/singleDetail', {
              id: patrolId
            }, 'get')
            if (re.status) {
              item = re.data
            } else {
              tool.handleShowToast(re.content, 'error')
            }
          }

          tool.postFrontStatus(`显示巡查详情页面#${item.id}`)

          tool.controlFormPage('巡查详情', async (refreshPage, toTop) => {
            const tf = tool.formPageControls
            return tool.formPageControls.main([
              //巡查信息
              tf.list.label(`${item.userData.username} 巡查于 ${item.createdAt_read}`, {
                fontSize: '26rpx',
                color: '#00555d'
              }),
              tf.list.labelArr([
                tf.list.labelArrItem(`#${item.id}`, {
                  fontWeight: 'bold',
                  color: '#00555d',
                  marginRight: '16rpx'
                }),
                tf.list.labelArrItem(`${item.status_read} • ${item.campusInfo.name}-${item.categoryInfo.name}`, {
                  marginRight: '1rem',
                  color: tool.getColorByPatrolStatus(item.status)
                })
              ], {
                fontSize: '32rpx',
                color: '#333',
                wordBreak: 'break-all',
                lineHeight: 1.5,
                whiteSpace: 'pre-wrap'
              }),
              tf.list.labelArr([
                tf.list.labelArrItem(item.desc)
              ], {
                fontSize: '32rpx',
                color: '#333',
                wordBreak: 'break-all',
                lineHeight: 1.5,
                whiteSpace: 'pre-wrap',
                marginTop: '-8rpx'
              }),
              ...await tool.execFunc(async () => {
                if (item.imageList.length || item.showMap) {
                  return [tf.list.imageSelector(item.imageList, true, 5, () => {}, false)]
                } else {
                  return []
                }
              }),
              tf.list.label(`截止于 ${item.endTime_read}`, {
                fontSize: '26rpx',
                color: '#333'
              }),
              // 隔断
              ...tf.list.splitArray('0rpx'),
              //延期信息
              ...await tool.execFunc(async () => {
                if (item.endTime_detail.num) {
                  return [
                    tf.list.label(`截止时间已延期${item.endTime_detail.num}次`, {
                      fontSize: '26rpx',
                      color: '#7100ac',
                      lineHeight: 1.5
                    }),
                    ...(() => {
                      let re = []
                      for (let i = 0; i < item.endTime_detail.list.length; i++) {
                        let cItem = item.endTime_detail.list[i]
                        re.push(tf.list.label(`第${i + 1}次（${cItem.size}）：${cItem.userData.username}${tool.isLogined() ? `【${cItem.userData.phone}】` : ''}从 ${cItem.from_read} 调整至 ${cItem.to_read}`, {
                          fontSize: '26rpx',
                          color: '#333',
                          lineHeight: 1.5
                        }))
                      }
                      return re
                    })(),
                    ...tf.list.splitArray('5rpx'),
                  ]
                } else {
                  return []
                }
              }),
              // 最终处理信息
              ...await tool.execFunc(async () => {
                if (item.detail.finalHandle) {
                  const idf = item.detail.finalHandle
                  return [
                    tf.list.label(`${idf.userData.username} 最终${idf.reject ? '拒绝' : '处理'}于 ${idf.createdAt_read}（第${item.detail.num.handle}次）`, {
                      fontSize: '26rpx',
                      color: idf.reject ? '#ff1d77' : 'rgb(0,120,215)'
                    }),
                    ...await tool.execFunc(async () => {
                      if (idf.reject) return []
                      let arr = [
                        tf.list.label(`时长 ${idf.usedTime}   ${idf.isOvertime ? `超时 ${idf.overtime}` : ''}`, {
                          fontSize: '26rpx',
                          color: '#333'
                        })
                      ]
                      return arr
                    }),
                    tf.list.labelArr([
                      tf.list.labelArrItem(idf.desc)
                    ], {
                      fontSize: '32rpx',
                      color: '#333',
                      wordBreak: 'break-all',
                      lineHeight: 1.5,
                      whiteSpace: 'pre-wrap',
                      marginTop: '0rpx'
                    }),
                    ...await tool.execFunc(async () => {
                      if (idf.imageList.length) {
                        return [tf.list.imageSelector(idf.imageList, true, 5, () => {}, false)]
                      } else {
                        return []
                      }
                    }),
                    // 隔断
                    ...tf.list.splitArray('0rpx'),
                  ]
                } else {
                  return []
                }
              }),
              // 最终评价信息
              ...await tool.execFunc(async () => {
                if (item.detail.finalFeedBack) {
                  const idfb = item.detail.finalFeedBack
                  return [
                    tf.list.label(`${idfb.userData.username} 最终评价于 ${idfb.createdAt_read}（第${item.detail.num.feedback}次）`, {
                      fontSize: '26rpx',
                      color: 'rgb(0,120,215)'
                    }),
                    tf.list.labelArr([
                      tf.list.labelArrItem((() => {
                        if (idfb.rating == 1) return '非常满意'
                        if (idfb.rating == 2) return '满意'
                        if (idfb.rating == 3) return '一般'
                        if (idfb.rating == 4) return '不满意'
                        if (idfb.rating == 5) return '非常不满意'
                      })()),
                      tf.list.labelArrItem(idfb.desc),
                    ], {
                      fontSize: '32rpx',
                      color: '#333',
                      wordBreak: 'break-all',
                      lineHeight: 1.5,
                      whiteSpace: 'pre-wrap',
                      marginTop: '0rpx'
                    }),
                    // 隔断
                    ...tf.list.splitArray('0rpx'),
                  ]
                } else {
                  return []
                }
              }),
              // 最终驳回信息
              ...await tool.execFunc(async () => {
                if (item.detail.finalReview) {
                  const idr = item.detail.finalReview
                  return [
                    tf.list.label(`${idr.userData.username} 最终驳回于 ${idr.createdAt_read}（第${item.detail.num.review}次）`, {
                      fontSize: '26rpx',
                      color: 'rgb(0,120,215)'
                    }),
                    tf.list.labelArr([
                      tf.list.labelArrItem(idr.desc)
                    ], {
                      fontSize: '32rpx',
                      color: '#333',
                      wordBreak: 'break-all',
                      lineHeight: 1.5,
                      whiteSpace: 'pre-wrap',
                      marginTop: '0rpx'
                    }),
                    // 隔断
                    ...tf.list.splitArray('0rpx'),
                  ]
                } else {
                  return []
                }
              }),
              ...await tool.execFunc(async () => {
                if (tool.isLogined()) {
                  return [
                    // 巡查人联系方式
                    ...await tool.execFunc(async () => {
                      return [
                        tf.list.label(`巡查人联系方式`, {
                          fontSize: '26rpx',
                          color: '#00555d'
                        }),
                        tf.list.buttonGroup(``, tool.getPhoneList([
                          tf.list.button(`${item.userData.username}`, () => {
                            if (tool.isLogined()) {
                              tool.postFrontStatus(`点击巡查人联系方式`)
                              if (tool.isMobile()) {
                                wx.makePhoneCall({
                                  phoneNumber: item.userData.phone,
                                })
                              } else {
                                wx.setClipboardData({
                                  data: item.userData.phone,
                                  success() {
                                    tool.handleShowToast(`已将手机号复制到剪切板`, 'success')
                                  },
                                });
                              }
                            }
                          }, undefined, 'text', `${item.userData.departmentInfo.name} ${item.userData.role}`, {
                            phone: item.userData.phone
                          })
                        ]))
                      ]
                    }),
                    // 负责人联系方式
                    ...await tool.execFunc(async () => {
                      let re = []
                      for (let i = 0; i < item.detail.progress.length; i++) {
                        let currentItem = item.detail.progress[i]
                        if (currentItem.tag == 'handle') {
                          re.push(
                            tf.list.button(`${currentItem.userData.username}`, () => {
                              if (tool.isLogined()) {
                                tool.postFrontStatus(`点击负责人联系方式`)
                                if (tool.isMobile()) {
                                  wx.makePhoneCall({
                                    phoneNumber: currentItem.userData.phone,
                                  })
                                } else {
                                  wx.setClipboardData({
                                    data: currentItem.userData.phone,
                                    success() {
                                      tool.handleShowToast(`已将手机号复制到剪切板`, 'success')
                                    },
                                  });
                                }
                              }
                            }, undefined, 'text', `${currentItem.userData.departmentInfo.name} ${currentItem.userData.role}`, {
                              phone: currentItem.userData.phone
                            })
                          )
                        }
                      }
                      if (!re.length) return []
                      return [
                        tf.list.label(),
                        tf.list.label(`负责人联系方式`, {
                          fontSize: '26rpx',
                          color: '#00555d'
                        }),
                        tf.list.buttonGroup(``, await tool.execFunc(async () => {
                          return tool.getPhoneList(re)
                        }))
                      ]
                    }),
                    // 审核人联系方式
                    ...await tool.execFunc(async () => {
                      let re = []
                      for (let i = 0; i < item.detail.progress.length; i++) {
                        let currentItem = item.detail.progress[i]
                        if (currentItem.tag == 'review') {
                          re.push(
                            tf.list.button(`${currentItem.userData.username}`, () => {
                              if (tool.isLogined()) {
                                tool.postFrontStatus(`点击审核人联系方式`)
                                if (tool.isMobile()) {
                                  wx.makePhoneCall({
                                    phoneNumber: currentItem.userData.phone,
                                  })
                                } else {
                                  wx.setClipboardData({
                                    data: currentItem.userData.phone,
                                    success() {
                                      tool.handleShowToast(`已将手机号复制到剪切板`, 'success')
                                    },
                                  });
                                }
                              }
                            }, undefined, 'text', `${currentItem.userData.departmentInfo.name} ${item.userData.role}`, {
                              phone: currentItem.userData.phone
                            })
                          )
                        }
                      }
                      if (!re.length) return []
                      return [
                        tf.list.label(),
                        tf.list.label(`审核人联系方式`, {
                          fontSize: '26rpx',
                          color: '#00555d'
                        }),
                        tf.list.buttonGroup(``, await tool.execFunc(async () => {
                          return tool.getPhoneList(re)
                        }))
                      ]
                    }),
                  ]
                } else {
                  return []
                }
              })
            ], undefined, tool.formPageControls.bottom([
              ...await tool.execFunc(async () => {
                let re = [
                  tf.topBottom.button('过程', 'process', () => {
                    tool.postFrontStatus(`巡查详情页面 - 过程`)
                    // tool.handleOpenPatrolLocation(item)
                    tool.handleShowPatrolFullProgress(item.id)
                  })
                ]
                if (item.showMap) {
                  re.push(tf.topBottom.button('定位', 'location', () => {
                    tool.handleOpenPatrolLocation(item)
                  }))
                }
                if ((userData && userData.id == item.userId && item.status == 1) || (userData && userData.isAdmin)) {
                  re.push(tf.topBottom.button('删除', 'delete', async () => {
                    tool.handleShowModel('是否删除此巡查？', true, async () => {
                      tool.postFrontStatus(`巡查详情页面 - 删除`)
                      tool.flow(async () => {
                        await tool.handleDeletePatrol(item.id)
                        tool.handleShowToastWithMask('成功')
                        await tool.wait(0.5)
                        wx.navigateBack()
                      }, (err) => {
                        tool.handleShowToast(`${err}`, 'error')
                      })
                    })
                  }))
                }
                if (item.permissions.edit && item.permissions.edit.show) {
                  re.push(tf.topBottom.button('修改', 'edit', async () => {
                    tool.handleShowActionSheet([
                      ...(() => {
                        if (item.permissions.edit.campusCategory) {
                          return [{
                            name: '修改校区类别',
                            callBack: async () => {
                              const form = {
                                campusId: '',
                                campusName: '',
                                categoryId: '',
                                categoryName: '',
                              }
                              tool.controlSettingsPage('修改校区类别', async (refreshPage_editCampusCategory) => {
                                return [{
                                    title: '选择校区类别',
                                    list: [{
                                        title: '校区',
                                        callBack: () => tool.select.campus((e) => {
                                          form.campusId = e.id
                                          form.campusName = e.name
                                          refreshPage_editCampusCategory()
                                        }),
                                        right: {
                                          type: 'text',
                                          value: (() => {
                                            if (form.campusId === '') return '未选择'
                                            return form.campusName
                                          })()
                                        }
                                      },
                                      {
                                        title: '类别',
                                        callBack: () => tool.select.category((e) => {
                                          form.categoryId = e.id
                                          form.categoryName = e.name
                                          refreshPage_editCampusCategory()
                                        }),
                                        right: {
                                          type: 'text',
                                          value: (() => {
                                            if (form.categoryId === '') return '未选择'
                                            return form.categoryName
                                          })()
                                        }
                                      },

                                    ]
                                  },
                                  {
                                    title: '操作',
                                    list: [{
                                      title: '确定',
                                      callBack: async () => {
                                        tool.flow(async () => {
                                          if (!form.campusId) throw '请选择校区'
                                          if (!form.categoryId) throw '请选择类别'
                                          let re = await tool.requestData('/patrol/edit/campusCategory', Object.assign({
                                            patrolId: item.id,
                                          }, form))
                                          if (re.status) {
                                            tool.handleShowToastWithMask('成功', 'success')
                                            await tool.wait(0.5)
                                            wx.navigateBack()
                                            tool.postFrontStatus(`巡查详情页面 - 修改 - 校区类别`)
                                            await handleUpdate()
                                            refreshPage()
                                          } else {
                                            throw re.content
                                          }
                                        }, err => tool.handleShowToast(`${err}`, 'error'))
                                      }
                                    }]
                                  }
                                ]
                              })
                            }
                          }]
                        } else {
                          return []
                        }
                      })()
                    ])
                    // tool.handleHandlePatrol(item.id, async () => {
                    //   tool.postFrontStatus(`巡查详情页面 - 处理`)
                    //   await handleUpdate()
                    //   refreshPage()
                    // })
                  }))
                }
                if (item.permissions.handle) {
                  re.push(tf.topBottom.button('处理', 'handle', async () => {
                    tool.handleHandlePatrol(item.id, async () => {
                      tool.postFrontStatus(`巡查详情页面 - 处理`)
                      await handleUpdate()
                      refreshPage()
                    })
                  }))
                }
                if (item.permissions.delay) {
                  re.push(tf.topBottom.button('延期', 'delay', async () => {
                    tool.handleDelayPatrol(item.id, item.endTime, async () => {
                      tool.postFrontStatus(`巡查详情页面 - 延期`)
                      await handleUpdate()
                      refreshPage()
                    })
                  }))
                }
                if (item.permissions.review) {
                  re.push(tf.topBottom.button('驳回', 'review', async () => {
                    tool.handleReviewPatrol(item.id, async () => {
                      tool.postFrontStatus(`巡查详情页面 - 驳回`)
                      await handleUpdate()
                      refreshPage()
                    })
                  }))
                }
                if (item.permissions.feedBack) {
                  re.push(tf.topBottom.button('评价', 'feedback', async () => {
                    tool.handleFeedBackPatrol(item.id, async () => {
                      tool.postFrontStatus(`巡查详情页面 - 评价`)
                      await handleUpdate()
                      refreshPage()
                    })
                  }))
                }
                if (item.permissions.priority) {
                  re.push(tf.topBottom.button('催办', 'priority', async () => {
                    tool.handlePriorityPatrol(item.id, async () => {
                      tool.postFrontStatus(`巡查详情页面 - 催办`)
                      await handleUpdate()
                      refreshPage()
                    })
                  }))
                }
                return re
              })
            ]))
          })

        } else {
          await tool.wait(0.05)
          tool.handleShowToast(re.content, 'error')
          tool.postFrontStatus(`打开巡查详情页面 - ${re.content}`)
        }
      },
    },
    userSearch(tips = [''], callBack = () => {}, enableMSelectDelete = true, enableMSelectOK = false) {
      const user_search = async () => {

        const data = {
          total: 0,
          list: [],
          form: {
            page: 1,
            size: 20,
            account: '',
            username: '',
            phone: '',
            role: '',
            isAdmin: undefined,
            departmentId: undefined,
            departmentName: undefined,
            isDisabled: undefined,
          },
          set(re) {
            if (!re.list.length) this.allowBottomGet = false
            this.list = tool.removeArrDup([...this.list, ...re.list], 'id')
            this.total = re.total
          },
          allowBottomGet: true,
          reset() {
            this.list = []
            this.form.page = 1
            this.allowBottomGet = true
          }
        }

        const get = async (form) => {
          let re = await tool.requestData('/admin/user/search', form, 'post')
          if (re.status) {
            return re.data
          } else {
            throw re.content
          }
        }

        tool.controlSettingsPage('查找用户', async (refreshPage_search_user_form) => {
          return [{
              title: '表单',
              list: [{
                  title: '账号（学号/工号）',
                  right: {
                    type: 'text',
                    value: data.form.account ? data.form.account : '不限'
                  },
                  callBack: async () => {
                    tool.handleShowActionSheet([{
                        name: '清空',
                        callBack: () => {
                          data.form.account = '';
                          refreshPage_search_user_form()
                        }
                      },
                      {
                        name: '输入',
                        callBack: () => tool.controlInput('账号（学号/工号）', '', 'singleText', data.form.account, async (value, done) => {
                          data.form.account = value
                          refreshPage_search_user_form()
                          done()
                        })
                      }
                    ])
                  }
                },
                {
                  title: '用户名',
                  right: {
                    type: 'text',
                    value: data.form.username ? data.form.username : '不限'
                  },
                  callBack: async () => {
                    tool.handleShowActionSheet([{
                        name: '清空',
                        callBack: () => {
                          data.form.username = ''
                          refreshPage_search_user_form()
                        }
                      },
                      {
                        name: '输入',
                        callBack: () => tool.controlInput('用户名', '', 'singleText', data.form.username, async (value, done) => {
                          data.form.username = value
                          refreshPage_search_user_form()
                          done()
                        })
                      }
                    ])
                  }
                },
                {
                  title: '手机号',
                  right: {
                    type: 'text',
                    value: data.form.phone ? data.form.phone : '不限'
                  },
                  callBack: async () => {
                    tool.handleShowActionSheet([{
                        name: '清空',
                        callBack: () => {
                          data.form.phone = ''
                          refreshPage_search_user_form()
                        }
                      },
                      {
                        name: '输入',
                        callBack: () => tool.controlInput('手机号', '', 'singleText', data.form.phone, async (value, done) => {
                          data.form.phone = value
                          refreshPage_search_user_form()
                          done()
                        })
                      }
                    ])
                  }
                },
                {
                  title: '角色',
                  right: {
                    type: 'text',
                    value: data.form.role ? data.form.role : '不限'
                  },
                  callBack: async () => {
                    wx.showActionSheet({
                      itemList: ['老师', '学生', '不限'],
                      success: (e) => {
                        e = e.tapIndex
                        if (e === 0) data.form.role = '老师'
                        if (e === 1) data.form.role = '学生'
                        if (e === 2) data.form.role = ''
                        refreshPage_search_user_form()
                      }
                    })
                  }
                },
                {
                  title: '管理员',
                  right: {
                    type: 'text',
                    value: data.form.isAdmin === undefined ? '不限' : (data.form.isAdmin ? '是' : '否')
                  },
                  callBack: async () => {
                    wx.showActionSheet({
                      itemList: ['是', '否', '不限'],
                      success: (e) => {
                        e = e.tapIndex
                        if (e === 0) data.form.isAdmin = 1
                        if (e === 1) data.form.isAdmin = 0
                        if (e === 2) data.form.isAdmin = undefined
                        refreshPage_search_user_form()
                      }
                    })
                  }
                },
                {
                  title: '部门',
                  right: {
                    type: 'text',
                    value: data.form.departmentName === undefined ? '不限' : data.form.departmentName
                  },
                  callBack: async () => {
                    tool.handleShowActionSheet([{
                        name: '清空',
                        callBack: () => {
                          data.form.departmentName = undefined
                          data.form.departmentId = undefined
                          refreshPage_search_user_form()
                        }
                      },
                      {
                        name: '选择',
                        callBack: () => tool.select.department(async (item) => {
                          data.form.departmentId = item.id
                          data.form.departmentName = item.name
                          refreshPage_search_user_form()
                        })
                      }
                    ])
                  }
                },
                {
                  title: '状态',
                  right: {
                    type: 'text',
                    value: (() => {
                      if (data.form.isDisabled === undefined) return '不限'
                      if (data.form.isDisabled === 0) return '正常登录'
                      if (data.form.isDisabled === 1) return '禁用'
                      if (data.form.isDisabled === 2) return '待审核'
                    })()
                  },
                  callBack: () => tool.handleShowActionSheet([{
                      name: '不限',
                      callBack: () => {
                        data.form.isDisabled = undefined;
                        refreshPage_search_user_form()
                      }
                    },
                    {
                      name: '正常登录',
                      callBack: () => {
                        data.form.isDisabled = 0;
                        refreshPage_search_user_form()
                      }
                    },
                    {
                      name: '禁用',
                      callBack: () => {
                        data.form.isDisabled = 1;
                        refreshPage_search_user_form()
                      }
                    },
                    {
                      name: '待审核',
                      callBack: () => {
                        data.form.isDisabled = 2;
                        refreshPage_search_user_form()
                      }
                    },
                  ])
                }
              ]
            },
            {
              title: '操作',
              list: [{
                title: '搜索',
                callBack: async () => {

                  data.reset()

                  const mSelect = {
                    open: false,
                    list: [],
                    isSelected(id) {
                      return this.list.indexOf(id) + 1 ? true : false
                    },
                    add(id) {
                      this.list.push(id)
                    },
                    delete(id) {
                      this.list = this.list.filter(item => item != id)
                      if (!this.list.length) this.open = false
                    },
                    itemClick(id) {
                      if (this.isSelected(id)) {
                        this.delete(id)
                      } else {
                        this.add(id)
                      }
                    }
                  }

                  tool.flow(async () => {
                    data.set(await get(data.form))
                    if (data.list.length == 0) throw '搜索结果为空'
                    tool.controlFormPage('查找用户', async (refreshPage_user_search_result) => {
                      const tf = tool.formPageControls
                      return tf.main([
                        tf.list.buttonGroup(`搜索结果（已加载${data.list.length}个，共${data.total}个）`, await tool.execFunc(async () => {
                          let t = []
                          for (let i = 0; i < data.list.length; i++) {
                            t.push(tf.list.button(`${mSelect.open ? `${mSelect.isSelected(data.list[i].id) ? '✓' : '◯'} ` : ``}${data.list[i].username}`, async () => {
                              if (mSelect.open) {
                                mSelect.itemClick(data.list[i].id)
                                mSelect.open = true
                                refreshPage_user_search_result()
                                return
                              }
                              try {
                                callBack([data.list[i]])
                              } catch (error) {

                              }
                            }, undefined, 'text', `${data.list[i].departmentInfo.name}`, {}, async () => {
                              if (!mSelect.open) {
                                mSelect.open = true
                                tool.handleShowToast('进入多选模式', 'none')
                              }
                              wx.vibrateShort({
                                type: 'light',
                              })
                              mSelect.itemClick(data.list[i].id)
                              refreshPage_user_search_result()
                            }))
                          }
                          return t
                        }))
                      ], undefined, await tool.execFunc(async () => {
                        if (mSelect.open) {
                          return tf.bottom([
                            tf.topBottom.button('退出多选', 'exit', () => {
                              mSelect.list = []
                              mSelect.open = false
                              refreshPage_user_search_result()
                            }),
                            ...await tool.execFunc(async () => {
                              if (enableMSelectDelete) {
                                return [tf.topBottom.button(`删除已选(${mSelect.list.length}个)`, 'delete', () => {
                                  tool.flow(async () => {
                                    await tool.admin.methods.deleteUsers(mSelect.list)
                                    mSelect.list = []
                                    mSelect.open = false
                                    data.reset()
                                    data.set(await get())
                                    refreshPage_user_search_result()
                                  }, err => tool.handleShowToast(`${err}`, 'error'))
                                }), ]
                              } else {
                                return []
                              }
                            }),
                            ...await tool.execFunc(async () => {
                              if (enableMSelectOK) {
                                return [
                                  tf.topBottom.button('确定', 'ok', () => {
                                    try {
                                      let t = tool.dcJSON(mSelect.list)
                                      for (let i = 0; i < t.length; i++) {
                                        for (let i1 = 0; i1 < data.list.length; i1++) {
                                          if (data.list[i1].id == t[i]) {
                                            t[i] = data.list[i1]
                                            break
                                          }
                                        }
                                      }
                                      callBack(t)
                                    } catch (error) {

                                    }
                                  })
                                ]
                              } else {
                                return []
                              }
                            })
                          ])
                        } else {
                          return undefined
                        }
                      }), () => {
                        tool.flow(async () => {
                          if (data.allowBottomGet === false) return
                          let form = Object.assign(tool.dcJSON(data.form), {
                            page: data.form.page + 1
                          })
                          data.set(await get(form))
                          data.form = form
                          refreshPage_user_search_result()
                        }, err => tool.handleShowToast(`${err}`, 'error'))
                      })
                    })
                  }, err => tool.handleShowToast(`${err}`, 'error'))
                }
              }]
            },
            ...await tool.execFunc(async () => {
              let t = tool.dcJSON(tips)
              for (let i = 0; i < t.length; i++) t[i] = {
                title: t[i]
              }
              return t
            }),
          ]
        })

      }
      user_search()
    },
    adminPage() {

      const dimension_campusCategory = async () => {
        const form = {
          campusId: undefined,
          categoryId: undefined,
          campusName: undefined,
          categoryName: undefined,
        }
        tool.controlSettingsPage('根据校区类别查找', async (refreshPage_selectCampusCategory) => {
          return [{
              title: '选择校区类别',
              list: [{
                  title: '校区',
                  right: {
                    type: 'text',
                    value: form.campusName
                  },
                  callBack: () => tool.select.campus((e) => {
                    console.log(e)
                    form.campusId = e.id
                    form.campusName = e.name
                    refreshPage_selectCampusCategory()
                  })
                },
                {
                  title: '类别',
                  right: {
                    type: 'text',
                    value: form.categoryName
                  },
                  callBack: () => tool.select.category((e) => {
                    console.log(e)
                    form.categoryId = e.id
                    form.categoryName = e.name
                    refreshPage_selectCampusCategory()
                  })
                },
              ]
            },
            {
              title: '操作',
              list: [{
                title: '搜索',
                callBack: () => tool.flow(async () => {
                  if (form.campusId === undefined) throw '选择校区'
                  if (form.categoryId === undefined) throw '选择类别'
                  const get = async () => {
                    let re = await tool.requestData('/admin/user/getListByCampusCategory', form)
                    if (re.status) {
                      return re.data
                    } else {
                      throw re.content
                    }
                  }
                  const data = {
                    lists: {}
                  }
                  data.lists = await get()
                  tool.controlSettingsPage(`用户列表`, async (refreshPage_ccr) => {
                    return [{
                        title: `具有${form.campusName}-${form.categoryName}相关权限的用户如下`
                      },
                      {
                        title: `负责人（${data.lists.handle.length}个）`,
                        list: (() => {
                          let re = []
                          for (let i = 0; i < data.lists.handle.length; i++) {
                            let current = data.lists.handle[i]
                            re.push({
                              title: `${current.username}`,
                              right: {
                                type: 'text',
                                value: current.account
                              },
                              callBack: () => tool.handleShowActionSheet([
                                // {
                                //   name: '用户信息',
                                //   callBack: () => tool.admin.editUserInfo(current.id)
                                // },
                                {
                                  name: '将此用户从当前权限列表中删除',
                                  callBack: () => tool.flow(async () => {
                                    await tool.permissions.delete(current.perId)
                                    data.lists = await get()
                                    refreshPage_ccr()
                                  }, err => tool.handleShowToast(`${err}`, 'error'))
                                }
                              ])
                            })
                          }
                          re.push({
                            title: '添加',
                            icon: 'add',
                            callBack: () => tool.page.userSearch(['提示：搜索并选择一个或多个用户'], (users) => tool.flow(async () => {
                              console.log(users)
                              for (let i = 0; i < users.length; i++) {
                                await tool.permissions.add(users[i].id, 1, form.campusId, form.categoryId)
                              }
                              data.lists = await get()
                              refreshPage_ccr()
                              wx.navigateBack({
                                delta: 2
                              })
                            }, err => tool.handleShowToast(`${err}`, 'error')), false, true)
                          })
                          return re
                        })()
                      },
                      {
                        title: `审核人（${data.lists.review.length}个）`,
                        list: (() => {
                          let re = []
                          for (let i = 0; i < data.lists.review.length; i++) {
                            let current = data.lists.review[i]
                            re.push({
                              title: `${current.username}`,
                              right: {
                                type: 'text',
                                value: current.account
                              },
                              callBack: () => tool.handleShowActionSheet([
                                // {
                                //   name: '用户信息',
                                //   callBack: () => tool.admin.editUserInfo(current.id)
                                // },
                                {
                                  name: '将此用户从当前权限列表中删除',
                                  callBack: () => tool.flow(async () => {
                                    await tool.permissions.delete(current.perId)
                                    data.lists = await get()
                                    refreshPage_ccr()
                                  }, err => tool.handleShowToast(`${err}`, 'error'))
                                }
                              ])
                            })
                          }
                          re.push({
                            title: '添加',
                            icon: 'add',
                            callBack: () => tool.page.userSearch(['提示：搜索并选择一个或多个用户'], (users) => tool.flow(async () => {
                              let errs = 0
                              for (let i = 0; i < users.length; i++) {
                                try {
                                  await tool.permissions.add(users[i].id, 2, form.campusId, form.categoryId)
                                } catch (error) {
                                  errs++
                                }
                              }
                              data.lists = await get()
                              refreshPage_ccr()
                              wx.navigateBack({
                                delta: 2
                              })
                              if (errs) tool.handleShowToast(`有${errs}个用户添加失败`, 'error')
                            }, err => tool.handleShowToast(`${err}`, 'error')), false, true)
                          })
                          return re
                        })()
                      }
                    ]
                  })
                }, err => tool.handleShowToast(`${err}`, 'error'))
              }]
            }
          ]
        })
      }
      tool.controlSettingsPage('管理员后台', async (refreshAdminPage) => {
        const feedback = async () => {
          return [{
            title: '后勤e码通',
            list: [{
                title: '启用后勤e码通功能',
                right: {
                  type: 'switch',
                  value: tool.store.getItem('home')?.feedBackData?.enable
                },
                async callBack(e, t) {
                  await tool.flow(async () => {
                    let re = await tool.requestData('/admin/feedback/enable', {
                      value: t
                    })
                    if (re.status) {
                      await tool.refreshHomeData()
                      refreshAdminPage()
                    } else {
                      throw re.content
                    }
                  }, err => {
                    wx.showToast({
                      title: `${err}`,
                      icon: 'error',
                      duration: 800
                    })
                  })
                }
              },
              {
                title: '每用户每天最多提交信息个数',
                right: {
                  type: 'text',
                  value: tool.store.getItem('home')?.feedBackData?.dayFeedBackNum
                },
                async callBack() {
                  tool.controlInput('输入每天最多反馈问题个数', '', 'singleText', tool.store.getItem('home')?.feedBackData?.dayFeedBackNum, async (e) => {
                    e = parseInt(e)
                    await tool.flow(async () => {
                      let re = await tool.requestData('/admin/feedback/dayFeedBackNum', {
                        value: e
                      })
                      if (re.status) {
                        wx.showToast({
                          title: '成功',
                          icon: 'success',
                          duration: 800
                        })
                        await tool.wait(0.8)
                        wx.navigateBack()
                        await tool.refreshHomeData()
                        refreshAdminPage()
                      } else {
                        throw re.content
                      }
                    }, err => {
                      wx.showToast({
                        title: `${err}`,
                        icon: 'error',
                        duration: 800
                      })
                    })
                  }, (e) => {
                    e = parseInt(e)
                    if (isNaN(e)) throw '输入正整数'
                    if (e < 1) throw '输入正整数'
                  })
                }
              },
              {
                title: '管理公告',
                async callBack() {
                  await tool.flow(async () => {
                    let re = await tool.requestData('/feedback/notice/list', {}, 'get')
                    if (re.status) {
                      let notice = re.data
                      const handleSaveNotice = async (arr) => {
                        let re = await tool.requestData('/admin/feedback/saveNotice', {
                          arr
                        })
                        if (re.status) {
                          notice = arr
                        } else {
                          throw re.content
                        }
                      }
                      tool.controlSettingsPage('管理公告', (refreshPage_notice) => {
                        return [{
                            list: (() => {
                              let re = []
                              for (let i = 0; i < notice.length; i++) {
                                re.push({
                                  title: notice[i].content,
                                  callBack() {
                                    tool.handleShowActionSheet([{
                                      name: '删除',
                                      callBack() {
                                        tool.handleShowModel('是否删除？', true, async () => {
                                          let re = JSON.parse(JSON.stringify([...notice.slice(0, i), ...notice.slice(i + 1)]))
                                          tool.flow(async () => {
                                            await handleSaveNotice(re)
                                            refreshPage_notice()
                                          }, err => wx.showToast({
                                            title: `${err}`,
                                            icon: 'error',
                                            duration: 800
                                          }))
                                        })
                                      }
                                    }])
                                  }
                                })
                              }
                              return re
                            })()
                          },
                          {
                            list: [{
                              title: '添加',
                              callBack: () => tool.controlInput('添加公告', '', 'multipleText', '', (e) => {
                                tool.flow(async () => {
                                  let re = JSON.parse(JSON.stringify(notice))
                                  re = [{
                                    content: e,
                                    createdAt: new Date(await tool.getServerTime())
                                  }, ...re]
                                  await handleSaveNotice(re)
                                  refreshPage_notice()
                                  wx.navigateBack()
                                }, err => wx.showToast({
                                  title: `${err}`,
                                  icon: 'error',
                                  duration: 800
                                }))
                              }, e => {
                                if (!e) throw '输入公告内容'
                                if (e.length > 64) throw '公告内容长度不能大于64'
                              })
                            }]
                          }
                        ]
                      })
                    } else {
                      throw re.content
                    }
                  }, err => wx.showToast({
                    title: `${err}`,
                    duration: 800,
                    icon: 'error'
                  }))

                }
              },
              {
                title: '管理轮播图',
                callBack() {
                  let banner = tool.store.getItem('home')?.feedBackData?.banner
                  if (banner === undefined) {
                    tool.handleShowToast('没有轮播图数据', 'error', 800)
                    return
                  }
                  tool.controlSettingsPage('管理轮播图', (refreshPage_banner) => {
                    return [{
                        title: banner.length ? '' : '没有轮播图',
                        list: (() => {
                          let re = []
                          for (let i = 0; i < banner.length; i++) {
                            console.log(banner[i].src)
                            re.push({
                              title: `${i + 1}`,
                              right: {
                                type: 'image',
                                src: banner[i].src
                              },
                              callBack() {
                                tool.handleShowActionSheet([{
                                    name: '删除',
                                    callBack() {
                                      tool.flow(async () => {
                                        let t = tool.dcJSON(banner)
                                        t = [...t.slice(0, i), ...t.slice(i + 1)]
                                        let re = await tool.requestData('/admin/feedback/saveBanners', {
                                          list: t
                                        })
                                        if (re.status) {
                                          banner = t
                                          refreshPage_banner()
                                        } else {
                                          throw re.content
                                        }
                                      }, err => tool.handleShowToast(`${err}`, 'error', 800))

                                      refreshPage_banner()
                                    }
                                  },
                                  {
                                    name: '预览',
                                    callBack() {
                                      console.log({
                                        urls: (() => {
                                          let t = tool.dcJSON(banner)
                                          for (let i = 0; i < t.length; i++) {
                                            t[i] = config.imagePrefix + t[i].src
                                          }
                                          return t
                                        })(),
                                        current: config.imagePrefix + banner[i].src
                                      })
                                      wx.previewImage({
                                        urls: (() => {
                                          let t = tool.dcJSON(banner)
                                          for (let i = 0; i < t.length; i++) {
                                            t[i] = config.imagePrefix + t[i].src
                                          }
                                          return t
                                        })(),
                                        current: config.imagePrefix + banner[i].src
                                      })
                                    }
                                  }
                                ])
                              }
                            })
                          }
                          return re
                        })()
                      },
                      {
                        list: [{
                          title: '添加',
                          callBack() {
                            tool.flow(async () => {
                              let re = await tool.chooseImage(1)
                              re = re[0]
                              re = await tool.compressImage(re)
                              re = await tool.uploadFileToServer(re, true)
                              try {
                                re = JSON.parse(re)
                              } catch (error) {

                              }
                              if (re.status) {
                                re = re.data
                              } else {
                                throw re.content
                              }
                              let t = tool.dcJSON(banner)
                              t.push({
                                src: re
                              })
                              re = await tool.requestData('/admin/feedback/saveBanners', {
                                list: t
                              })
                              if (re.status) {
                                banner = t
                                refreshPage_banner()
                              } else {
                                throw re.content
                              }
                            }, err => tool.handleShowToast(`${err}`, 'error', 800))
                          }
                        }]
                      }
                    ]
                  })
                }
              },
              {
                title: '每天下午四点向负责人发送日报',
                right: {
                  type: 'switch',
                  value: tool.store.getItem('home')?.feedBackSendDailyHandleReport
                },
                async callBack(a, e) {
                  await tool.flow(async () => {
                    let re = await tool.requestData('/setting/set', {
                      key: 'feedBackSendDailyHandleReport',
                      value: e
                    })
                    if (re.status) {
                      await tool.refreshHomeData()
                      refreshAdminPage()
                    } else {
                      throw re.content
                    }
                  }, err => {
                    tool.handleShowToast(`${err}`, 'error')
                  })
                }
              }
            ]
          }]
        }
        const notification = async () => {
          return [{
            title: '通知',
            list: [{
                title: '启用微信服务通知',
                right: {
                  type: 'switch',
                  value: tool.getHomeData().postWeChatMessage
                },
                callBack: () => tool.flow(async () => {
                  await tool.settings.set('postWeChatMessage', !tool.getHomeData().postWeChatMessage)
                  await tool.refreshHomeData()
                  refreshAdminPage()
                }, err => tool.handleShowToast(`${err}`, 'error'))
              },
              {
                title: '启用短信通知',
                right: {
                  type: 'switch',
                  value: tool.getHomeData().sendMessage
                },
                callBack: () => tool.flow(async () => {
                  await tool.settings.set('sendMessage', !tool.getHomeData().sendMessage)
                  await tool.refreshHomeData()
                  refreshAdminPage()
                }, err => tool.handleShowToast(`${err}`, 'error'))
              },
              {
                title: '发送通知',
                callBack: async () => {
                  const form = {
                    type: '',
                    userIds: [],
                    campusId: undefined,
                    categoryId: undefined,
                    content: '',
                    departmentId: undefined,
                    sendMessage: false,
                    role: ''
                  }
                  const sendRequest = async () => {
                    let re = await tool.requestData('/admin/notification/send', form)
                    if (re.status) {

                    } else {
                      throw re.content
                    }
                  }
                  tool.controlFormPage('填写通知内容', async (refreshPage_inputContent) => {
                    const tf = tool.formPageControls
                    return tool.formPageControls.main([
                      tf.list.textarea('通知内容', form.content, (e) => {
                        form.content = e
                        refreshPage_inputContent()
                      }),
                      tf.list.label('通知内容会出现在通知页面上，用微信服务通知和短信通知（可选）提醒用户'),
                      tf.list.buttonGroup('', [
                        tf.list.button('短信通知', (d, e) => {
                          form.sendMessage = e;
                          refreshPage_inputContent()
                        }, undefined, 'switch', form.sendMessage)
                      ])
                    ], undefined, tf.bottom([
                      tf.topBottom.button('下一步', 'ok', async () => {
                        if (!form.content) {
                          tool.handleShowToast('输入通知内容', 'error')
                          return
                        }
                        tool.controlSettingsPage('选择接收人', async (refreshPage_selectReciver) => {
                          return [{
                            list: [{
                                title: '全体用户',
                                callBack: async () => tool.flow(async () => {
                                  form.type = 'toAll'
                                  await sendRequest()
                                  tool.handleShowToastWithMask('成功')
                                  await tool.wait(0.5)
                                  wx.navigateBack({
                                    delta: 2
                                  })
                                }, err => tool.handleShowToast(`${err}`, 'error'))
                              },
                              {
                                title: '选择用户',
                                callBack: async () => tool.page.userSearch(['选择至少一个用户并发送通知'], (ids) => {
                                  for (let i = 0; i < ids.length; i++) ids[i] = ids[i].id
                                  form.userIds = ids
                                  tool.flow(async () => {
                                    form.type = 'toUsers'
                                    await sendRequest()
                                    tool.handleShowToastWithMask('成功')
                                    await tool.wait(0.5)
                                    wx.navigateBack({
                                      delta: 4
                                    })
                                  }, err => tool.handleShowToast(`${err}`, 'error'))
                                }, false, true)
                              },
                              {
                                title: '校区-类别负责人',
                                callBack: async () => tool.select.campus(async (campusInfo) => {
                                  await tool.wait(0.4)
                                  form.campusId = campusInfo.id
                                  tool.select.category((categoryInfo) => {
                                    form.categoryId = categoryInfo.id
                                    tool.flow(async () => {
                                      form.type = 'toHandleGroup'
                                      await sendRequest()
                                      tool.handleShowToastWithMask('成功')
                                      await tool.wait(0.5)
                                      wx.navigateBack({
                                        delta: 4
                                      })
                                    }, err => tool.handleShowToast(`${err}`, 'error'))
                                  })
                                })
                              },
                              {
                                title: '校区-类别审核人',
                                callBack: async () => tool.select.campus(async (campusInfo) => {
                                  await tool.wait(0.4)
                                  form.campusId = campusInfo.id
                                  tool.select.category((categoryInfo) => {
                                    form.categoryId = categoryInfo.id
                                    tool.flow(async () => {
                                      form.type = 'toReviewGroup'
                                      await sendRequest()
                                      tool.handleShowToastWithMask('成功')
                                      await tool.wait(0.5)
                                      wx.navigateBack({
                                        delta: 4
                                      })
                                    }, err => tool.handleShowToast(`${err}`, 'error'))
                                  })
                                })
                              },
                              {
                                title: '角色',
                                callBack: async () => {
                                  wx.showActionSheet({
                                    itemList: ['老师', '学生'],
                                    success: async (e) => {
                                      form.type = 'toRole'
                                      e = e.tapIndex
                                      if (e === 0) {
                                        tool.flow(async () => {
                                          form.role = '老师'
                                          await sendRequest()
                                          tool.handleShowToastWithMask('成功')
                                          await tool.wait(0.5)
                                          wx.navigateBack({
                                            delta: 2
                                          })
                                        }, err => tool.handleShowToast(`${err}`, 'error'))

                                      }
                                      if (e === 1) {
                                        tool.flow(async () => {
                                          form.role = '学生'
                                          await sendRequest()
                                          tool.handleShowToastWithMask('成功')
                                          await tool.wait(0.5)
                                          wx.navigateBack({
                                            delta: 2
                                          })
                                        }, err => tool.handleShowToast(`${err}`, 'error'))

                                      }
                                    }
                                  })
                                }
                              },
                              {
                                title: '部门',
                                callBack: async () => tool.select.department(async (item) => {
                                  form.type = 'toDepartment'
                                  form.departmentId = item.id
                                  tool.flow(async () => {
                                    await sendRequest()
                                    tool.handleShowToastWithMask('成功')
                                    await tool.wait(0.5)
                                    wx.navigateBack({
                                      delta: 3
                                    })
                                  }, err => tool.handleShowToast(`${err}`, 'error'))
                                })
                              },
                            ]
                          }]
                        })
                      })
                    ]))
                  })
                }
              }
            ]
          }]
        }
        const user = async () => {
          return [{
            title: '用户',
            list: [{
                title: '根据用户信息查找',
                callBack: () => tool.page.userSearch([
                  '如何审核新用户？ 将状态字段设为“待审核”，其他字段全部为不限，然后开始搜索，就能看到待审核的新用户。',
                  '如何批量删除用户？ 搜索出现用户列表之后，长按单个用户，进入多选模式，选择需要删除的用户，点击底部的“删除已选”按钮。'
                ], (item) => tool.admin.editUserInfo(item[0].id))
              },
              {
                title: '新用户审核后才能使用',
                right: {
                  type: 'switch',
                  value: tool.getHomeData().accountVer
                },
                callBack: () => tool.flow(async () => {
                  await tool.settings.set('accountVer', !tool.getHomeData().accountVer)
                  await tool.refreshHomeData()
                  refreshAdminPage()
                }, err => tool.handleShowToast(`${err}`, 'error'))
              },
              {
                title: '在登录页面上显示注册入口',
                right: {
                  type: 'switch',
                  value: tool.getHomeData().allowReg
                },
                callBack: () => tool.flow(async () => {
                  await tool.settings.set('allowReg', !tool.getHomeData().allowReg)
                  await tool.refreshHomeData()
                  refreshAdminPage()
                }, err => tool.handleShowToast(`${err}`, 'error'))
              },
              {
                title: '导出Excel',
                callBack: () => tool.flow(async () => {
                  let re = await tool.requestData('/user/export', {}, 'get')
                  if (re.status) {
                    tool.handleShowModel('表格生成后有通知提醒', false)

                  } else {
                    throw re.content
                  }
                }, err => tool.handleShowToast(`${err}`, 'error'))
              },
            ]
          }]
        }
        const patrol = async () => {
          return [{
            title: '巡查',
            list: [{
                title: '满意度调查环节',
                right: {
                  type: 'switch',
                  value: tool.getHomeData().progress_feedBack
                },
                callBack: () => tool.flow(async () => {
                  await tool.settings.set('progress_feedBack', !tool.getHomeData().progress_feedBack)
                  await tool.refreshHomeData()
                  refreshAdminPage()
                }, err => tool.handleShowToast(`${err}`, 'error'))
              },
              {
                title: '审核环节',
                right: {
                  type: 'switch',
                  value: tool.getHomeData().progress_review
                },
                callBack: () => tool.flow(async () => {
                  await tool.settings.set('progress_review', !tool.getHomeData().progress_review)
                  await tool.refreshHomeData()
                  refreshAdminPage()
                }, err => tool.handleShowToast(`${err}`, 'error'))
              },
              {
                title: '每用户每天最多巡查个数',
                right: {
                  type: 'text',
                  value: `${tool.getHomeData().dailyPatrolLimitPerUser}个`,
                },
                callBack: async () => {
                  tool.controlInput('每用户每天最多巡查个数', '单位：个', 'number', tool.getHomeData().dailyPatrolLimitPerUser, async (value, done) => {
                    tool.flow(async () => {
                      await tool.updateSetting('dailyPatrolLimitPerUser', value)
                      await tool.refreshHomeData()
                      tool.handleShowToastWithMask('成功')
                      await tool.wait(0.5)
                      refreshAdminPage()
                      done()
                    }, err => tool.handleShowToast(`${err}`, 'error'))
                  }, (value) => {
                    value = parseInt(value)
                    if (isNaN(value)) throw '应为正整数'
                    if (value < 1) throw '应为正整数'
                  })

                }
              },
              {
                title: '默认截止几个工作日后',
                right: {
                  type: 'text',
                  value: `${tool.getHomeData().newPatrolDefaultWorkDays}天`,
                },
                callBack: async () => {
                  tool.controlInput('默认截止几个工作日后', '单位：天', 'number', tool.getHomeData().newPatrolDefaultWorkDays, async (value, done) => {
                    tool.flow(async () => {
                      await tool.updateSetting('newPatrolDefaultWorkDays', value)
                      await tool.refreshHomeData()
                      tool.handleShowToastWithMask('成功')
                      await tool.wait(0.5)
                      refreshAdminPage()
                      done()
                    }, err => tool.handleShowToast(`${err}`, 'error'))
                  }, (value) => {
                    value = parseInt(value)
                    if (isNaN(value)) throw '应为不大于30的自然数'
                    if (value < 1 || value > 30) throw '应为不大于30的自然数'
                  })

                }
              },
              {
                title: '新建巡查通知延后时间',
                right: {
                  type: 'text',
                  value: `${tool.getHomeData().newPatrolSendNotificationWaitTime}分钟`
                },
                callBack: () => tool.controlInput('新建巡查通知延后时间', '单位：分钟', 'number', tool.getHomeData().newPatrolSendNotificationWaitTime, async (value, done) => {
                  tool.flow(async () => {
                    await tool.updateSetting('newPatrolSendNotificationWaitTime', value)
                    await tool.refreshHomeData()
                    tool.handleShowToastWithMask('成功')
                    await tool.wait(0.5)
                    refreshAdminPage()
                    done()
                  }, err => tool.handleShowToast(`${err}`, 'error'))
                }, (value) => {
                  value = parseInt(value)
                  if (isNaN(value)) throw '应为自然数'
                  if (value < 0) throw '应为自然数'
                })
              },
              {
                title: '巡查延期最长天数',
                right: {
                  type: 'text',
                  value: `${tool.getHomeData().maxDelayTime}天`,
                },
                callBack: async () => {
                  tool.controlInput('巡查延期最长天数', '单位：天', 'number', tool.getHomeData().maxDelayTime, async (value, done) => {
                    tool.flow(async () => {
                      await tool.updateSetting('maxDelayTime', value)
                      await tool.refreshHomeData()
                      tool.handleShowToastWithMask('成功')
                      await tool.wait(0.5)
                      refreshAdminPage()
                      done()
                    }, err => tool.handleShowToast(`${err}`, 'error'))
                  }, (value) => {
                    value = parseInt(value)
                    if (isNaN(value)) throw '应为自然数'
                    if (value < 1) throw '应为自然数'
                  })

                }
              },
              {
                title: '删除未处理巡查',
                callBack: () => tool.controlInput('删除未处理巡查', '请输入“删除未处理巡查”', 'singleText', '', (value, done) => {
                  tool.handleShowModel('点击确定开始删除全部的未处理的巡查', true, async () => {
                    let re = await tool.requestData('/patrol/deleteAllNotHandle')
                    if (re.status) {
                      tool.handleShowToast('成功')
                      await tool.wait(0.5)
                      done()
                    } else {
                      tool.handleShowToast(re.content, 'error')
                    }
                  })
                }, (value) => {
                  if (value != '删除未处理巡查') throw '输入有误'
                })
              },
              {
                title: '导出Excel',
                callBack: () => tool.page.getSearchPatrolForm(async (form) => tool.flow(async () => {
                  form.size = 500000
                  delete form.finalId
                  let re = await tool.requestData('/patrol/genExcel', form)
                  if (re.status) {
                    tool.handleShowModel('表格生成后有通知提醒', false, () => {
                      wx.navigateBack()
                    })

                  } else {
                    throw re.content
                  }
                }, err => tool.handleShowToast(`${err}`, 'error')))
              },
            ]
          }]
        }
        const dimension = async () => {
          const handle = async (isCampus = true, op = '', id = undefined, name = undefined) => {
            let re = await tool.requestData(`/${isCampus ? 'campus' : 'category'}/${op}`, {
              id,
              name
            })
            if (re.status) {
              return re.data
            } else {
              throw re.content
            }
          }
          return [{
            title: '多维度',
            list: [{
                title: '校区',
                callBack: async () => {
                  const get = async () => {
                    let re = await tool.requestData('/campus/getList', {}, 'get')
                    if (re.status) {
                      return re.data.default
                    } else {
                      throw re.content
                    }
                  }
                  let list = []
                  tool.flow(async () => {
                    list = await get()
                    tool.controlSettingsPage('管理校区', async (refreshPage_campuses) => {
                      let re = []
                      for (let i = 0; i < list.length; i++) {
                        re.push({
                          title: list[i].name,
                          callBack: async (e) => {
                            wx.showActionSheet({
                              itemList: ['删除', '修改'],
                              success: async (e) => {
                                e = e.tapIndex
                                if (e === 0) {
                                  tool.handleShowModel('是否删除？', true, () => tool.flow(async () => {
                                    await handle(true, 'delete', list[i].id)
                                    tool.handleShowToast('成功')
                                    list = await get()
                                    refreshPage_campuses()
                                  }, err => tool.handleShowToast(`${err}`, 'error')))
                                }
                                if (e === 1) {
                                  tool.controlInput('修改校区名称', '', 'singleText', list[i].name, async (value, done) => tool.flow(async () => {
                                    await handle(true, 'update', list[i].id, value)
                                    list = await get()
                                    refreshPage_campuses()
                                    tool.handleShowToast('成功')
                                    await tool.wait(0.5)
                                    done()
                                  }, err => tool.handleShowToast(`${err}`, 'error')), (value) => {
                                    if (!value) throw '输入内容'
                                  })
                                }
                              }
                            })
                          }
                        })
                      }
                      re.push({
                        title: '添加',
                        icon: 'add',
                        callBack: () => tool.controlInput('输入名称', '', 'singleText', '', async (value, done) => {
                          await handle(true, 'add', undefined, value)
                          list = await get()
                          refreshPage_campuses()
                          tool.handleShowToast('成功')
                          await tool.wait(0.5)
                          done()
                        })
                      })
                      return [{
                        list: re
                      }]
                    })
                  }, err => tool.handleShowToast(`${err}`, 'error'))
                }
              },
              {
                title: '类别',
                callBack: async () => {
                  const get = async () => {
                    let re = await tool.requestData('/category/getList', {}, 'get')
                    if (re.status) {
                      return re.data.default
                    } else {
                      throw re.content
                    }
                  }
                  let list = []
                  tool.flow(async () => {
                    list = await get()
                    tool.controlSettingsPage('管理类别', async (refreshPage_categories) => {
                      let re = []
                      for (let i = 0; i < list.length; i++) {
                        re.push({
                          title: list[i].name,
                          callBack: async (e) => {
                            wx.showActionSheet({
                              itemList: ['删除', '修改'],
                              success: async (e) => {
                                e = e.tapIndex
                                if (e === 0) {
                                  tool.handleShowModel('是否删除？', true, () => tool.flow(async () => {
                                    await handle(false, 'delete', list[i].id)
                                    tool.handleShowToast('成功')
                                    list = await get()
                                    refreshPage_categories()
                                  }, err => tool.handleShowToast(`${err}`, 'error')))
                                }
                                if (e === 1) {
                                  tool.controlInput('修改类别名称', '', 'singleText', list[i].name, async (value, done) => tool.flow(async () => {
                                    await handle(false, 'update', list[i].id, value)
                                    list = await get()
                                    refreshPage_categories()
                                    tool.handleShowToast('成功')
                                    await tool.wait(0.5)
                                    done()
                                  }, err => tool.handleShowToast(`${err}`, 'error')), (value) => {
                                    if (!value) throw '输入内容'
                                  })
                                }
                              }
                            })
                          }
                        })
                      }
                      re.push({
                        title: '添加',
                        icon: 'add',
                        callBack: () => tool.controlInput('输入名称', '', 'singleText', '', async (value, done) => {
                          await handle(false, 'add', undefined, value)
                          list = await get()
                          refreshPage_categories()
                          tool.handleShowToast('成功')
                          await tool.wait(0.5)
                          done()
                        })
                      })
                      return [{
                        list: re
                      }]
                    })
                  }, err => tool.handleShowToast(`${err}`, 'error'))
                }
              },
              {
                title: '设置校区类别负责人和审核人',
                callBack: dimension_campusCategory
              },
            ]
          }]
        }
        return [
          ...await feedback(),
          ...await patrol(),
          ...await user(),
          ...await notification(),
          ...await dimension()
        ]
      })
    },
    patrolListPage(title = '', getPatrolList = () => {}, openCallBack = () => {}, moreCallBack = () => {}, toBottom = () => {}, total = undefined) {
      tool.controlFormPage(title, async (refreshPage) => {
        let list = getPatrolList()

        tool.store.onChange('deletePatrol', () => {
          let t = tool.store.getItem('deletePatrol')
          list = tool.deleteListLocalById(list, t.id)
          refreshPage()
        })
        tool.store.onChange('updatePatrolInList', () => {
          list = tool.updateListLocalByItem(list, tool.store.getItem('updatePatrolInList'))
          refreshPage()
        })

        return tool.formPageControls.main([
          tool.formPageControls.list.patrolList(list, openCallBack, moreCallBack)
        ], undefined, tool.formPageControls.bottom((() => {
          if (total === undefined) {
            return []
          } else {
            return [
              tool.formPageControls.topBottom.label(`共${total}个巡查`)
            ]
          }
        })()), () => toBottom(() => {
          refreshPage()
        }))
      })
    },
    async userTasks(groupName, campusId, categoryId, isDelay, userId) {
      const data = {
        list: [],
        getFinalId() {
          if (this.list.length) {
            return this.list[this.list.length - 1].id
          } else {
            return undefined
          }
        }
      }
      const get = async () => {
        let re = await tool.requestData('/patrol/myTasks', {
          groupName,
          campusId,
          categoryId,
          isDelay,
          userId,
          finalId: data.getFinalId(),
          size: 10
        })
        if (re.status) {
          return re.data
        } else {
          throw re.content
        }
      }
      tool.flow(async () => {
        data.list = tool.removeArrDup([...data.list, ...await get()], 'id')
        if (!data.list.length) throw '无巡查'
        tool.page.patrolListPage('巡查列表', () => {
          return data.list
        }, (e) => {
          tool.page.patrol.info(e.id)
        }, (e) => {
          tool.handleShowPatrolMoreList(e)
        }, async (refreshPage) => {
          data.list = tool.removeArrDup([...data.list, ...await get()], 'id')
          refreshPage()
        })
      }, err => tool.handleShowToast(`${err}`, 'error'))
    },
    async userTasks_feedBack(groupName, campusId, categoryId, userId, campusName, categoryName) {
      if (groupName === 'preToHandle_feedBack') {
        tool.page.searchFeedBack({
          campusId,
          categoryId
        }, `${campusName}${categoryName}反馈`)
      }
    },
    async myTasks() {
      const get = async () => {
        let re = await tool.requestData('/user/myTasks', {}, 'get')
        if (re.status) {
          return re.data
        } else {
          throw re.content
        }
      }
      tool.flow(async () => {
        let data = await get()
        if (data.isBlank) throw '我的事务为空'
        const handleButtonClick = (groupName, campusId, categoryId, num, isDelay) => {
          console.log(groupName, campusId, categoryId, num, isDelay)
          if (groupName == 'admin') {

          } else {
            if (!num) {
              tool.handleShowToast(`没有任务`, 'error')
            } else {
              tool.page.userTasks(groupName, campusId, categoryId, isDelay, store.getItem('userData').id)
            }
          }
        }
        const handleButtonClick_feedBack = (groupName, campusId, categoryId, num, campusName, categoryName) => {
          console.log(groupName, campusId, categoryId, num)
          if (groupName == 'admin') {

          } else {
            if (!num) {
              tool.handleShowToast(`没有任务`, 'error')
            } else {
              tool.page.userTasks_feedBack(groupName, campusId, categoryId, store.getItem('userData').id, campusName, categoryName)
            }
          }
        }
        let refreshMyTasks = () => {}
        store.onChange('deletePatrol', async (item) => {
          tool.flow(async () => {
            let re = await get()
            if (re.isBlank) {
              tool.handleShowToastWithMask(`我的事务为空`, 'error', 2000)
              await tool.wait(1.5)
              wx.navigateBack()
            } else {
              data = re
              refreshMyTasks()
            }
          }, err => tool.handleShowToast(`${err}`, 'error'))

        })
        store.onChange('updatePatrolInList', async (item) => {
          tool.flow(async () => {
            let re = await get()
            if (re.isBlank) {
              tool.handleShowToastWithMask(`我的事务为空`, 'error', 2000)
              await tool.wait(1.5)
              wx.navigateBack()
            } else {
              data = re
              refreshMyTasks()
            }
          }, err => tool.handleShowToast(`${err}`, 'error'))

        })
        tool.controlSettingsPage('我的事务', async (refreshPage_myTasks) => {
          refreshMyTasks = () => refreshPage_myTasks()
          return [
            ...await tool.execFunc(async () => {
              if (data.admin && data.admin.length) {
                return [{
                  title: '我是管理员',
                  list: (() => {
                    let re = []
                    for (let i = 0; i < data.admin.length; i++) {
                      const item = data.admin[i]
                      re.push({
                        title: item.name,
                        right: {
                          type: 'text',
                          value: `${item.num}个`
                        },
                        callBack: () => {
                          if (item.name.indexOf('巡查') + 1) {
                            tool.page.searchPatrol();
                            tool.postFrontStatus('点击我的事务 - 管理员管理全部巡查')
                          }
                          if (item.name.indexOf('反馈') + 1) {
                            tool.feedback.showAllOrSearchOptions()
                          }
                        }
                      })
                    }
                    return re
                  })()
                }, ]
              } else {
                return []
              }
            }),
            ...await tool.execFunc(async () => {
              if (data.preToHandle.length) {
                return [{
                  title: '需要我处理的巡查',
                  list: (() => {
                    let re = []
                    for (let i = 0; i < data.preToHandle.length; i++) {
                      const item = data.preToHandle[i]
                      re.push({
                        title: `${item.name}`,
                        right: {
                          type: 'text',
                          value: `${item.num}个`
                        },
                        callBack: () => {
                          handleButtonClick('preToHandle', item.campusInfo.id, item.categoryInfo.id, item.num, item.isDelay ? true : false);

                          tool.postFrontStatus(`点击我的事务 - 需要我处理的巡查 ${item.campusInfo.name} ${item.categoryInfo.name} `)
                        }
                      })
                    }
                    return re
                  })()
                }, ]
              } else {
                return []
              }
            }),
            ...await tool.execFunc(async () => {
              if (data.preToHandle_feedBack.length) {
                return [{
                  title: '需要我处理的反馈',
                  list: (() => {
                    let re = []
                    for (let i = 0; i < data.preToHandle_feedBack.length; i++) {
                      const item = data.preToHandle_feedBack[i]
                      re.push({
                        title: `${item.name}`,
                        right: {
                          type: 'text',
                          value: `${item.num}个`
                        },
                        callBack: () => {
                          console.log(item)
                          handleButtonClick_feedBack('preToHandle_feedBack', item.campusInfo.id, item.categoryInfo.id, item.num, item.campusInfo.name, item.categoryInfo.name);

                          tool.postFrontStatus(`点击我的事务 - 需要我处理的反馈 ${item.campusInfo.name} ${item.categoryInfo.name} `)
                        }
                      })
                    }
                    return re
                  })()
                }, ]
              } else {
                return []
              }
            }),
            ...await tool.execFunc(async () => {
              if (data.preToReview.length) {
                return [{
                  title: '需要我审核的巡查',
                  list: (() => {
                    let re = []
                    for (let i = 0; i < data.preToReview.length; i++) {
                      const item = data.preToReview[i]
                      re.push({
                        title: `${item.name}`,
                        right: {
                          type: 'text',
                          value: `${item.num}个`
                        },
                        callBack: () => {
                          handleButtonClick('preToReview', item.campusInfo.id, item.categoryInfo.id, item.num, item.isDelay ? true : false);
                          tool.postFrontStatus(`点击我的事务 - 需要我审核的巡查 ${item.campusInfo.name} ${item.categoryInfo.name} `)
                        }
                      })
                    }
                    return re
                  })()
                }, ]
              } else {
                return []
              }
            }),
            ...await tool.execFunc(async () => {
              if (data.waitingForHandle.length) {
                return [{
                  title: '我提交的待处理的巡查',
                  list: (() => {
                    let re = []
                    for (let i = 0; i < data.waitingForHandle.length; i++) {
                      const item = data.waitingForHandle[i]
                      re.push({
                        title: `${item.name}`,
                        right: {
                          type: 'text',
                          value: `${item.num}个`
                        },
                        callBack: () => {
                          handleButtonClick('waitingForHandle', item.campusInfo.id, item.categoryInfo.id, item.num, item.isDelay ? true : false);

                          tool.postFrontStatus(`点击我的事务 - 我提交的待处理的巡查 ${item.campusInfo.name} ${item.categoryInfo.name} `)
                        }
                      })
                    }
                    return re
                  })()
                }, ]
              } else {
                return []
              }
            }),
            ...await tool.execFunc(async () => {
              if (data.waitingForRating.length) {
                return [{
                  title: '我提交的待评价的巡查',
                  list: (() => {
                    let re = []
                    for (let i = 0; i < data.waitingForRating.length; i++) {
                      const item = data.waitingForRating[i]
                      re.push({
                        title: `${item.name}`,
                        right: {
                          type: 'text',
                          value: `${item.num}个`
                        },
                        callBack: () => {
                          handleButtonClick('waitingForRating', item.campusInfo.id, item.categoryInfo.id, item.num, item.isDelay ? true : false);
                          tool.postFrontStatus(`点击我的事务 - 我提交的待评价的巡查 ${item.campusInfo.name} ${item.categoryInfo.name} `)
                        }
                      })
                    }
                    return re
                  })()
                }, ]
              } else {
                return []
              }
            }),
          ]
        })
      }, err => tool.handleShowToast(`${err}`, 'error'))
    },
    async myHistoryTasks() {
      this.userTasks('myHistory', 0, 0, undefined, store.getItem('userData').id)
    },
    searchPatrol(fm = undefined, title = '') {
      const search = async (e) => {
        let form = tool.dcJSON(e)
        let list = []
        let size = 10
        const finalId = () => {
          if (list.length) {
            return list[list.length - 1].id
          } else {
            return undefined
          }
        }
        const get = async () => {
          let re = await tool.requestData('/patrol/searchWithTotal', Object.assign(form, {
            finalId: finalId(),
            size
          }))
          if (re.status) {
            return re.data
          } else {
            throw re.content
          }
        }
        const getList = () => {
          return list
        }
        tool.flow(async () => {
          let re = await get()
          list = re.list
          if (!list.length) throw '无巡查'
          tool.page.patrolListPage(title, () => {
            return getList()
          }, (e) => tool.page.patrol.info(e.id), (e) => tool.handleShowPatrolMoreList(e), async (refreshPage) => {
            console.log(finalId())
            tool.flow(async () => {
              list = tool.removeArrDup([...list, ...(await get()).list], 'id')
              refreshPage()
            }, err => tool.handleShowToast(`${err}`, 'error'))
          }, re.total)
        }, err => tool.handleShowToast(`${err}`, 'error'))
      }
      if (fm === undefined) {
        tool.page.getSearchPatrolForm(async (e) => {
          search(e)
        })
      } else {
        search(tool.dcJSON(fm))
      }
    },
    getSearchFeedBackForm(callBack = () => {}) {
      let form = {}
      const btn = (title, callBack, rightType, rightValue) => {
        if (!rightType) {
          return {
            title,
            callBack
          }
        }
        return {
          title,
          callBack,
          right: {
            type: rightType,
            value: rightValue
          }
        }
      }
      const valueDisplay = (val) => {
        if (val === undefined) return ''
        return val
      }
      tool.controlSettingsPage('设置反馈查询条件', (refreshPage_setFeedBackSearchPro) => {
        const select = (field, input) => {
          tool.handleShowActionSheet([{
              name: '清除',
              callBack() {
                if (typeof field === 'string') field = [field]
                field.forEach(item => {
                  delete form[item]
                })
                refreshPage_setFeedBackSearchPro()
              }
            },
            {
              name: '输入',
              callBack() {
                input()
              }
            },
          ])
        }
        return [{
            list: [

              btn('ID', () => select('id', () => tool.controlInput('ID', '', 'singleText', form.id, e => {
                e = parseInt(e)
                form.id = e
                refreshPage_setFeedBackSearchPro()
                wx.navigateBack()
              }, e => {
                e = parseInt(e)
                if (isNaN(e) || e < 1) throw '应为正整数'
              })), 'text', `${valueDisplay(form.id)}`),

              btn('创建时间 开始', () => select('createdAtStart', () => tool.controlPicker('创建时间开始', '', 'dateTime', form.createdAtStart, [], e => {
                form.createdAtStart = e
                refreshPage_setFeedBackSearchPro()
                wx.navigateBack()
              }, e => {
                if (e.indexOf('null') !== -1 || e.indexOf('undefined') !== -1) throw '未选择'
              })), 'text', `${valueDisplay(form.createdAtStart)}`),

              btn('创建时间 结束', () => select('createdAtEnd', () => tool.controlPicker('创建时间结束', '', 'dateTime', form.createdAtEnd, [], e => {
                form.createdAtEnd = e
                refreshPage_setFeedBackSearchPro()
                wx.navigateBack()
              }, e => {
                if (e.indexOf('null') !== -1 || e.indexOf('undefined') !== -1) throw '未选择'
              })), 'text', `${valueDisplay(form.createdAtEnd)}`),

              btn('内容', () => select('content', () => tool.controlInput('内容', '', 'multipleText', form.content, e => {
                form.content = e
                refreshPage_setFeedBackSearchPro()
                wx.navigateBack()
              }, e => {
                if (!e) throw '未输入'
              })), 'text', `${valueDisplay(form.content)}`),

              btn('角色', () => tool.handleShowActionSheet([{
                  name: '老师',
                  callBack() {
                    form.role = 'teacher'
                    refreshPage_setFeedBackSearchPro()
                  }
                },
                {
                  name: '学生',
                  callBack() {
                    form.role = 'student'
                    refreshPage_setFeedBackSearchPro()
                  }
                },
                {
                  name: '清除',
                  callBack() {
                    delete form.role
                    refreshPage_setFeedBackSearchPro()
                  }
                },
              ]), 'text', `${valueDisplay((() => {
              if (form.role === 'student') return '学生'
              if (form.role === 'teacher') return '老师'
            })())}`),

              btn('校区', () => select(['campusId', 'campusName'], () => tool.select.campus(e => {
                form.campusId = e.id
                form.campusName = e.name
                refreshPage_setFeedBackSearchPro()
              })), 'text', `${valueDisplay(form.campusName)}`),

              btn('类别', () => select(['categoryId', 'categoryName'], () => tool.select.category(e => {
                form.categoryId = e.id
                form.categoryName = e.name
                refreshPage_setFeedBackSearchPro()
              })), 'text', `${valueDisplay(form.categoryName)}`),

              btn('有图片', () => tool.handleShowActionSheet([{
                  name: '是',
                  callBack() {
                    form.hasImage = true
                    refreshPage_setFeedBackSearchPro()
                  }
                },
                {
                  name: '否',
                  callBack() {
                    form.hasImage = false
                    refreshPage_setFeedBackSearchPro()
                  }
                },
                {
                  name: '清除',
                  callBack() {
                    delete form.hasImage
                    refreshPage_setFeedBackSearchPro()
                  }
                },
              ]), 'text', `${valueDisplay((() => {
              if (form.hasImage === true) return '是'
              if (form.hasImage === false) return '否'
            })())}`),

              btn('有位置', () => tool.handleShowActionSheet([{
                  name: '是',
                  callBack() {
                    form.hasLocation = true
                    refreshPage_setFeedBackSearchPro()
                  }
                },
                {
                  name: '否',
                  callBack() {
                    form.hasLocation = false
                    refreshPage_setFeedBackSearchPro()
                  }
                },
                {
                  name: '清除',
                  callBack() {
                    delete form.hasLocation
                    refreshPage_setFeedBackSearchPro()
                  }
                },
              ]), 'text', `${valueDisplay((() => {
              if (form.hasLocation === true) return '是'
              if (form.hasLocation === false) return '否'
            })())}`),

              btn('姓名', () => select('name', () => tool.controlInput('姓名', '', 'singleText', form.name, e => {
                form.name = e
                refreshPage_setFeedBackSearchPro()
                wx.navigateBack()
              }, e => {
                if (!e) throw '未输入'
              })), 'text', `${valueDisplay(form.name)}`),

              btn('手机号', () => select('phone', () => tool.controlInput('手机号', '', 'singleText', form.phone, e => {
                form.phone = e
                refreshPage_setFeedBackSearchPro()
                wx.navigateBack()
              }, e => {
                if (!e) throw '未输入'
              })), 'text', `${valueDisplay(form.phone)}`),

              btn('部门', () => select(['departmentId', 'departmentName'], () => tool.select.department(e => {
                form.departmentId = e.id
                form.departmentName = e.name
                refreshPage_setFeedBackSearchPro()
              })), 'text', `${valueDisplay(form.departmentName)}`),

              btn('回复负责人用户', () => select(['answerUserId', 'answerUserName'], () => tool.page.userSearch(['选择用户'], (e) => {
                e = e[0]
                form.answerUserName = e.username
                form.answerUserId = e.id
                refreshPage_setFeedBackSearchPro()
                wx.navigateBack({
                  delta: 2
                })
              }, false, true)), 'text', `${valueDisplay(form.answerUserName)}`),

            ]
          },
          {
            list: [
              btn('确定', () => {
                try {
                  callBack(form)
                } catch (error) {

                }
              })
            ]
          }
        ]
      })
    },
    searchFeedBack(fm, title) {
      tool.flow(async () => {
        let getting = false
        const get = async (finalId) => {
          let re = await tool.requestData('/feedback/query', {
            form: fm,
            finalId
          })
          if (re.status) {
            return re.data
          } else {
            throw re.content
          }
        }
        let data = await get()
        tool.controlFormPage(title, (refreshPage_feedBackRes) => {
          tool.store.onChange('feedBack_deleteItem', (id) => {
            data.data = data.data.filter(item => item.id !== id)
            refreshPage_feedBackRes()
          })
          tool.store.onChange('feedBack_updateItem', (item) => {
            for (let i = 0; i < data.data.length; i++) {
              if (data.data[i].id === item.id) {
                data.data[i] = {
                  ...data.data[i],
                  ...item
                }
              }
            }
            refreshPage_feedBackRes()
          })
          return tool.formPageControls.main((() => {
            let res = []
            for (let i = 0; i < data.data.length; i++) {
              res.push(tool.formPageControls.list.feedBack(data.data[i]))
            }
            return res
          })(), undefined, tool.formPageControls.bottom([
            tool.formPageControls.topBottom.label(`共${data.total}个反馈`)
          ]), () => {
            if (getting) return
            getting = true
            let finalId = data.data[data.data.length - 1].id
            tool.flow(async () => {
              let re = await get(finalId)
              data.data = [...data.data, ...re.data]
              data.total = re.total
              refreshPage_feedBackRes()
              if (re.data.length) {
                getting = false
              }
            }, err => wx.showToast({
              title: `${err}`,
              duration: 800,
              icon: 'error'
            }))
          })
        })
      }, err => wx.showToast({
        title: `${err}`,
        icon: 'error',
        duration: 800
      }))
    }
  },
  async handleReloadIndex() {
    let t = store.getItem('mainCurrentPageIndex')
    store.setItem('mainCurrentPageIndex', -1)
    await tool.wait(0.001)
    store.setItem('mainCurrentPageIndex', t)
  },
  async handleExitLogin(okCallBack = () => {}) {
    tool.handleShowModel('是否退出？', true, async () => {
      await tool.flow(async () => {
        let re = await tool.requestData('/user/exitLogin')
        if (re.status == 1) {
          try {
            okCallBack()
          } catch (error) {

          }
        } else {
          throw re.content
        }
      }, (err) => {
        tool.handleShowToast(err, 'error')
      })
    })
  },
  redirectToIndex() {
    tool.store.setItem('requestShowLoading', false)
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  controlFormPage(title = '', init = (refreshPage) => {
    return {
      top: {
        ve: 'center',
        ho: 'center',
        list: []
      },
      bottom: {
        ve: 'center',
        ho: 'center',
        list: []
      },
      list: [{
          type: 'buttonGroup',
          title: '',
          list: []
        },
        {
          type: 'input',
          style: {},
          config: {}
        }
      ],
      toBottomCallBack: () => {}
    }
  }) {
    store.setItem('controlFormPage', {
      title,
      init
    })
    wx.navigateTo({
      url: '/pages/form/form',
    })
  },
  formPageControls: {
    list: {
      input(placeHolder = '', defaultValue = '', onInput = (value) => {}, style = {}) {
        return {
          type: 'input',
          config: {
            placeHolder,
            defaultValue,
            onInput
          },
          style: tool.convertStyleObjectToString(style)
        }
      },
      splitArray(height = '40rpx', style = {}) {
        return [{
            type: 'label',
            config: {
              style: tool.convertStyleObjectToString(Object.assign({
                width: '100%',
                height
              }, style))
            }
          },
          {
            type: 'label',
            config: {
              style: tool.convertStyleObjectToString(Object.assign({
                width: 'calc(100vw)',
                transform: 'translateX(-32rpx)',
                height: '1rpx',
                backgroundColor: 'rgb(230,230,230)'
              }, style))
            }
          },
          {
            type: 'label',
            config: {
              style: tool.convertStyleObjectToString(Object.assign({
                width: '100%',
                height
              }, style))
            }
          },
        ]
      },
      textarea(placeHolder = '', defaultValue = '', onInput = (value) => {}, style = {}) {
        return {
          type: 'textarea',
          config: {
            placeHolder,
            defaultValue,
            onInput
          },
          style: tool.convertStyleObjectToString(style)
        }
      },
      imageSelector(list = [], preview = false, count = 5, onChange = (list) => {}, fullURL = false, showMap, location1, location2) {
        return {
          type: 'imageSelector',
          config: {
            count,
            onChange,
            list,
            preview,
            fullURL,
            showMap,
            location1,
            location2
          }
        }
      },
      buttonGroup(title = '', list = []) {
        return {
          type: 'buttonGroup',
          config: {
            title,
            list
          }
        }
      },
      button(title = '', callBack = () => {}, icon = undefined, rightType = undefined, rightValueOrSrc = '', otherKeys = {}, longPressCallBack = () => {}) {
        return {
          title,
          callBack,
          longPressCallBack,
          icon,
          right: (() => {
            if (rightType == 'text') {
              return {
                type: 'text',
                value: rightValueOrSrc
              }
            }
            if (rightType == 'image' || rightType == 'webImage') {
              return {
                type: rightType,
                src: rightValueOrSrc
              }
            }
            if (rightType == 'switch') {
              return {
                type: rightType,
                value: rightValueOrSrc
              }
            }
          })(),
          ...otherKeys
        }
      },
      label(title = '', style = {}) {
        return {
          type: 'label',
          config: {
            title,
            style: tool.convertStyleObjectToString(style)
          }
        }
      },
      labelArr(list = [], style = {}) {
        return {
          type: 'labelArr',
          config: {
            style: tool.convertStyleObjectToString(style)
          },
          list
        }
      },
      labelArrItem(title = '', style = {}) {
        return {
          config: {
            title,
            style: tool.convertStyleObjectToString(style)
          }
        }
      },
      patrolList(list, openCallBack = () => {}, moreCallBack = () => {}) {
        return {
          type: 'patrolList',
          config: {
            list,
            openCallBack,
            moreCallBack
          }
        }
      },
      conditionItem(condiion = false, item) {
        if (condiion) {
          let re = item()
          if (Array.isArray(re)) return re
          return [re]
        } else {
          return []
        }
      },
      feedBack(item) {
        return {
          type: 'feedBack',
          config: {
            item
          }
        }
      }
    },
    topBottom: {
      label(content = '', style = {}) {
        return {
          type: 'label',
          config: {
            content
          },
          style: tool.convertStyleObjectToString(style)
        }
      },
      input(placeHolder = '', defaultValue = '', onInput = (e) => {}, style = {}) {
        return {
          type: 'input',
          config: {
            placeHolder,
            defaultValue,
            onInput
          },
          style: tool.convertStyleObjectToString(style)
        }
      },
      button(title = '', icon = undefined, onClick = () => {}, style = {}) {
        return {
          type: 'button',
          config: {
            title,
            icon,
            onClick
          },
          style: tool.convertStyleObjectToString(style)
        }
      }
    },
    top(list = [], ve = 'center', ho = 'center') {
      return {
        list,
        ve,
        ho
      }
    },
    bottom(list = [], ve = 'center', ho = 'center') {
      return {
        list,
        ve,
        ho
      }
    },
    main(list = [], top = undefined, bottom = undefined, toBottomCallBack = () => {}) {
      return {
        list,
        top,
        bottom,
        toBottomCallBack
      }
    }
  },
  convertStyleObjectToString(styleObject) {
    return Object.entries(styleObject)
      .map(([key, value]) => {
        const kebabKey = key.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
        return `${kebabKey}: ${value}`;
      })
      .join('; ');
  },
  chooseImages(maxCount = 5) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: maxCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          resolve(res.tempFilePaths);
        },
        fail(err) {
          reject(err);
        }
      });
    });
  },
  getNextWorkday(date, workdays = 3) {
    let resultDate = new Date(date.getTime());
    let count = 0;
    while (count < workdays) {
      resultDate.setDate(resultDate.getDate() + 1);
      let dayOfWeek = resultDate.getDay();
      if (dayOfWeek >= 1 && dayOfWeek <= 5) {
        count++;
      }
    }
    return resultDate;
  },
  handleShowPatrolMoreList(item) {
    tool.postFrontStatus(`显示巡查更多菜单#${item.id}`)
    let ls = [
      ...(() => {
        if (item.permissions.handle) {
          return ['处理']
        } else {
          return []
        }
      })(),
      ...(() => {
        if (item.permissions.delay) {
          return ['延期']
        } else {
          return []
        }
      })(),
      ...(() => {
        if (item.permissions.feedback) {
          return ['评价']
        } else {
          return []
        }
      })(),
      ...(() => {
        if (item.permissions.review) {
          return ['驳回']
        } else {
          return []
        }
      })(),
      ...(() => {
        if (item.permissions.delete) {
          return ['删除']
        }
        return []
      })(),
      ...(() => {
        if (item.imageList.length) {
          return ['查看巡查图片']
        } else {
          return []
        }
      })(),
      ...(() => {
        if (item.finalHandle !== undefined) {
          return ['查看最终处理结果图片']
        } else {
          return []
        }
      })(),
      ...(() => {
        if (item.showMap) {
          return ['查看位置']
        } else {
          return []
        }
      })(),
    ]
    wx.showActionSheet({
      itemList: ls,
      success: async (e) => {
        e = e.tapIndex
        let selected = ls[e]
        tool.postFrontStatus(`巡查更多菜单 - ${selected}`)
        if (selected == '处理') {
          tool.handleHandlePatrol(item.id)
        }
        if (selected == '驳回') {
          tool.handleReviewPatrol(item.id)
        }
        if (selected == '评价') {
          tool.handleFeedBackPatrol(item.id)
        }
        if (selected == '延期') {
          tool.handleDelayPatrol(item.id, item.endTime)
        }
        if (selected == '查看位置') {
          tool.handleOpenPatrolLocation(item)
        }
        if (selected == '查看巡查图片') {
          wx.previewImage({
            urls: (() => {
              let t = item.imageList
              for (let i = 0; i < t.length; i++) {
                t[i] = `${config.imagePrefix}${t[i]}`
              }
              return t
            })(),
          })
        }
        if (selected == '详情') {
          tool.page.patrol.info(item.id)
        }
        if (selected == '删除') {
          tool.handleShowModel(`是否删除？`, true, () => {
            tool.flow(async () => {
              await tool.handleDeletePatrol(item.id)
              tool.handleShowToast('成功')
            }, (err) => {
              tool.handleShowToast(`${err}`, 'error')
            })
          })
        }
      }
    })
  },
  deleteRepeatPatrolsAndSort(arr) {
    let tt = arr
    for (let i = 0; i < tt.length; i++) {
      if (tt[i] === undefined) continue
      for (let i1 = i + 1; i1 < tt.length; i1++) {
        if (tt[i1] === undefined) continue
        if (tt[i].id == tt[i1].id) {
          tt[i1] = undefined
        }
      }
    }
    return tt.filter(item => item !== undefined).sort((a, b) => {
      return new Date(b.createdAt) - new Date(a.createdAt)
    })
  },
  async handleDeletePatrol(id) {
    let re = await tool.requestData('/patrol/delete', {
      id
    })
    if (re.status) {
      store.setItem(`deletePatrol`, {
        id
      })
    } else {
      throw re.content
    }
  },
  async handleDelayPatrol(id, defaultValue, okCallBack = () => {}) {
    tool.controlPicker('选择新的截止时间', '', 'dateTime', tool.formatDateTime(new Date(defaultValue)), [], async (value, done) => {
      let re = await tool.requestData('/patrol/delay', {
        patrolId: id,
        datetime: value
      })
      if (re.status) {
        tool.handleShowToastWithMask('成功')
        await tool.wait(0.5)
        tool.updateGlobalPatrolInfoInList(id)
        done()
        try {
          okCallBack()
        } catch (error) {

        }
      } else {
        tool.handleShowToast(`${re.content}`, 'error')
      }
    })
  },
  async handleHandlePatrol(patrolId, okCallBack = () => {}) {
    const handleSelect = () => {
      return new Promise((resolve, reject) => {
        wx.showActionSheet({
          itemList: ['填写处理结果', '拒绝处理'],
          success(e) {
            e = e.tapIndex
            if (e === 0) {
              return resolve(0)
            }
            if (e === 1) {
              return resolve(1)
            }
          },
          fail() {
            return resolve(undefined)
          }
        })
      })
    }
    let select = await handleSelect()
    if (select === undefined) return
    if (select === 1) {
      const form = {
        patrolId,
        userId: store.getItem('userData').id,
        reject: 1,
        desc: '',
        image1: '',
        image2: '',
        image3: '',
        image4: '',
        image5: ''
      }
      tool.controlInput('填写拒绝原因', '', 'multipleText', '', async (value, done) => {
        form.desc = value
        let re = await tool.requestData('/patrol/handle', {
          patrolId,
          form
        })
        if (re.status) {
          tool.handleShowToastWithMask('成功')
          await tool.wait(0.5)
          done()
          tool.updateGlobalPatrolInfoInList(patrolId)
          try {
            okCallBack()
          } catch (error) {

          }
        } else {
          tool.handleShowToast(re.content, 'error')
        }
      }, (value) => {
        if (!value) throw '不能为空'
        if (value.length > 128) throw '拒绝原因长度不能大于128'
      })
      return
    }
    const form = {
      patrolId,
      userId: store.getItem('userData').id,
      reject: 0,
      desc: '',
      image1: '',
      image2: '',
      image3: '',
      image4: '',
      image5: ''
    }
    let imageList = []
    tool.controlFormPage('处理巡查', async (refreshPage) => {
      const tf = tool.formPageControls
      return tf.main([
        tf.list.textarea('文字描述', form.desc, (value) => {
          form.desc = value
        }),
        tf.list.imageSelector(imageList, false, 5, (list) => {
          imageList = list
          refreshPage()
        }, true),
      ], undefined, tf.bottom([
        tf.topBottom.button(`提交`, 'ok', async () => {
          await tool.flow(async () => {
            if (!form.desc) throw '输入描述'
            if (!imageList.length) throw '添加图片'
            let currentImageIndex = 1
            wx.showLoading({
              title: '正在上传',
            })
            let form_for_upload = tool.dcJSON(form)
            for (let i = 0; i < imageList.length; i++) {
              let re = await tool.compressImage(imageList[i])
              re = await tool.uploadFileToServer(re, false)
              try {
                re = JSON.parse(re)
              } catch (error) {

              }
              if (re.status) {
                form_for_upload[`image${currentImageIndex}`] = re.data
                currentImageIndex++
              }
            }
            wx.showLoading({
              title: '正在提交',
            })
            let re = await tool.requestData('/patrol/handle', {
              patrolId,
              form: form_for_upload
            })
            if (re.status) {
              tool.handleShowToastWithMask('成功')
              await tool.wait(0.5)
              tool.updateGlobalPatrolInfoInList(patrolId)
              try {
                okCallBack()
              } catch (error) {

              }
              wx.navigateBack()
            } else {
              tool.handleShowToast(re.content, 'error')
              if (form_for_upload.image1) tool.requestData('/patrol/deleteFile', {
                fileName: form_for_upload.image1
              })
              if (form_for_upload.image2) tool.requestData('/patrol/deleteFile', {
                fileName: form_for_upload.image2
              })
              if (form_for_upload.image3) tool.requestData('/patrol/deleteFile', {
                fileName: form_for_upload.image3
              })
              if (form_for_upload.image4) tool.requestData('/patrol/deleteFile', {
                fileName: form_for_upload.image4
              })
              if (form_for_upload.image5) tool.requestData('/patrol/deleteFile', {
                fileName: form_for_upload.image5
              })
            }
          }, (err) => {
            tool.handleShowToast(`${err}`, 'error')
          })
        })
      ]))
    })
  },
  async handlePriorityPatrol(patrolId, okCallBack = () => {}) {
    tool.flow(async () => {
      let re = await tool.requestData('/patrol/priority', {
        patrolId
      })
      if (re.status) {
        tool.handleShowToast('成功')
        try {
          okCallBack()
        } catch (error) {

        }
      } else {
        throw re.content
      }
    }, err => tool.handleShowToast(`${err}`, 'error'))
  },
  isMobile() {
    const systemInfo = wx.getSystemInfoSync();
    if (systemInfo.platform === 'ios' || systemInfo.platform === 'android') {
      return true
    } else if (systemInfo.platform === 'windows' || systemInfo.platform === 'mac') {
      return false
    }
    return false
  },
  getColorByPatrolStatus(status) {
    if (status === 1) return 'rgb(0,120,215)'
    if (status === 2) return '#7100ac'
    if (status === 3) return '#01bd40'
    if (status === 4) return '#686868'
    if (status === 5) return '#ff1d77'
    return '#333'
  },
  handleOpenPatrolLocation(item) {
    if (!item.showMap) {
      tool.handleShowToast(`巡查人未设置位置`)
      return
    }
    if (tool.isMobile()) {
      wx.openLocation({
        latitude: parseFloat(item.location1),
        longitude: parseFloat(item.location2),
        name: item.desc,
        address: `${item.campusInfo.name}-${item.categoryInfo.name}`
      })
    } else {
      wx.setClipboardData({
        data: `https://uri.amap.com/marker?position=${item.location2},${item.location1}`,
      })
      tool.handleShowToast(`已复制位置链接`, 'error')
      // tool.handleOpenLocationInWebView(item.location1, item.location2)
    }
  },
  async updateGlobalPatrolInfoInList(id) {
    let re = await tool.requestData('/patrol/singleSimple', {
      id
    }, 'get')
    if (re.status) {
      store.setItem('updatePatrolInList', re.data)
    }
  },
  updateListLocalByItem(list, item) {
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == item.id) {
        list[i] = Object.assign(list[i], item)
        break
      }
    }
    return list
  },
  deleteListLocalById(list, id) {
    for (let i = 0; i < list.length; i++) {
      if (list[i].id == id) {
        if (list[i].topTitle) {
          if (list[i + 1]) {
            if (!list[i + 1].topTitle) list[i + 1].topTitle = list[i].topTitle
          }
        }
        list[i] = undefined
      }
    }
    return list.filter(item => item != undefined)
  },
  handleSubWXNotif() {
    tool.postFrontStatus(`点击订阅提醒`)
    return new Promise((resolve, reject) => {
      wx.requestSubscribeMessage({
        tmplIds: ['uK_iS4p6Yre6pyg_JpiUcxM0xiSJ88QEOPGrW3t95zU'], // 模板 ID
        success(res) {
          if (res['uK_iS4p6Yre6pyg_JpiUcxM0xiSJ88QEOPGrW3t95zU'] === 'accept') {
            tool.handleShowToast('订阅成功')
            tool.store.setItem('subNotif', true)
            resolve({
              status: 1,
              content: `用户同意`
            })
            console.log('用户同意订阅');
          } else {
            tool.store.setItem('subNotif', true)
            resolve({
              status: 0,
              content: `用户拒绝`
            })
            console.log('用户拒绝订阅');
          }
        },
        fail(err) {
          tool.postFrontStatus(`订阅失败 ${err.toString()}`)
          tool.store.setItem('subNotif', true)
          resolve({
            status: 0,
            content: `${err}`
          })
          console.error('订阅失败', err);
        }
      })
    })
  },
  getHomeData() {
    let t = store.getItem('home')
    if (!t) throw '服务器异常或者手机网络链接有问题'
    return t
  },
  async updateSetting(key, value) {
    let re = await tool.requestData('/setting/set', {
      key,
      value
    })
    if (re.status) {

    } else {
      throw re.content
    }
  },
  async refreshHomeData() {
    let re = await tool.requestData('/user/home', {
      code: await tool.getLoginCode()
    }, 'get', false)
    if (re.status == 1) {
      this.store.setItem('home', re.data)
      this.store.setItem('openId', re.data?.openId)
      this.store.setItem('feedBackData', re.data?.feedBackData)
      return re.data
    } else {
      throw '服务器异常或者手机网络链接有问题'
    }
  },
  handleReviewPatrol(patrolId, okCallBack = () => {}) {
    tool.controlInput('驳回巡查', '', 'multipleText', '', async (value, done) => {
      let re = await tool.requestData('/patrol/review', {
        patrolId,
        desc: value
      })
      if (re.status) {
        tool.handleShowToast('成功')
        await tool.wait(0.5)
        done()
        try {
          okCallBack()
        } catch (error) {

        }
        tool.updateGlobalPatrolInfoInList(patrolId)
      } else {
        tool.handleShowToast(re.content, 'error')
      }
    }, (value) => {
      if (!value) throw '输入驳回原因'
      if (value.length > 128) throw '不超过128个字'
    })
  },
  handleFeedBackPatrol(patrolId, okCallBack = () => {}) {
    const tf = tool.formPageControls
    const form = {
      rating: 0,
      desc: '',
      patrolId
    }
    tool.controlFormPage('评价巡查', async (refreshPage) => {
      return tool.formPageControls.main([
        tf.list.buttonGroup('选择评分', [
          tf.list.button('非常满意', () => {
            form.rating = 1;
            refreshPage();
          }, undefined, 'text', form.rating == 1 ? '选中' : ''),
          tf.list.button('满意', () => {
            form.rating = 2;
            refreshPage();
          }, undefined, 'text', form.rating == 2 ? '选中' : ''),
          tf.list.button('一般', () => {
            form.rating = 3;
            refreshPage();
          }, undefined, 'text', form.rating == 3 ? '选中' : ''),
          tf.list.button('不满意', () => {
            form.rating = 4;
            refreshPage();
          }, undefined, 'text', form.rating == 4 ? '选中' : ''),
          tf.list.button('非常不满意', () => {
            form.rating = 5;
            refreshPage();
          }, undefined, 'text', form.rating == 5 ? '选中' : ''),
        ]),
        tf.list.label('', {
          display: 'inline-block',
          height: '0rpx'
        }),
        tf.list.textarea('文字描述（选填）', form.desc, (e) => {
          form.desc = e
        })
      ], undefined, tool.formPageControls.bottom([
        tf.topBottom.button('提交', 'ok', () => {
          tool.flow(async () => {
            if (!form.rating) throw '选择评分'
            let re = await tool.requestData('/patrol/feedBack', {
              patrolId,
              ...form
            })
            if (re.status) {
              tool.handleShowToastWithMask('成功')
              await tool.wait(0.5)
              wx.navigateBack()
              try {
                okCallBack()
              } catch (error) {

              }
              tool.updateGlobalPatrolInfoInList(patrolId)
            } else {
              throw re.content
            }
          }, err => tool.handleShowToast(`${err}`, 'error'))
        })
      ]))
    })
  },
  async handleShowPatrolFullProgress(patrolId) {
    let re = await tool.requestData('/patrol/singleDetail', {
      id: patrolId
    }, 'get')
    if (re.status) {
      const item = re.data
      const tf = tool.formPageControls
      tool.controlFormPage('巡查处理过程', async () => {
        return tool.formPageControls.main([
          //巡查信息
          tf.list.label(`${item.userData.username} 巡查于 ${item.createdAt_read}`, {
            fontSize: '26rpx',
            color: '#00555d'
          }),
          tf.list.labelArr([
            tf.list.labelArrItem(`#${item.id}`, {
              fontWeight: 'bold',
              color: '#00555d',
              marginRight: '16rpx'
            }),
            tf.list.labelArrItem(`${item.status_read} • ${item.campusInfo.name}-${item.categoryInfo.name}`, {
              marginRight: '1rem',
              color: tool.getColorByPatrolStatus(item.status)
            })
          ], {
            fontSize: '32rpx',
            color: '#333',
            wordBreak: 'break-all',
            lineHeight: 1.5,
            whiteSpace: 'pre-wrap'
          }),
          tf.list.labelArr([
            tf.list.labelArrItem(item.desc)
          ], {
            fontSize: '32rpx',
            color: '#333',
            wordBreak: 'break-all',
            lineHeight: 1.5,
            whiteSpace: 'pre-wrap',
            marginTop: '-22rpx'
          }),
          ...await tool.execFunc(async () => {
            if (item.imageList.length || item.showMap) {
              return [tf.list.imageSelector(item.imageList, true, 5, () => {}, false)]
            } else {
              return []
            }
          }),
          tf.list.label(`截止于 ${item.endTime_read}`, {
            fontSize: '26rpx',
            color: '#333'
          }),
          ...tf.list.splitArray('0rpx'),
          //流程
          ...await tool.execFunc(async () => {
            let res = []

            for (let i = 0; i < item.detail.progress.length; i++) {
              let subItem = item.detail.progress[i]
              if (subItem.tag == 'handle') {
                const idf = subItem
                res = [...res, ...[
                  tf.list.label(`${idf.userData.username} ${idf.reject ? '拒绝' : '处理'}于 ${idf.createdAt_read}`, {
                    fontSize: '26rpx',
                    color: idf.reject ? '#ff1d77' : 'rgb(0,120,215)'
                  }),
                  ...await tool.execFunc(async () => {
                    if (idf.reject) return []
                    let arr = [
                      tf.list.label(`时长 ${idf.usedTime}   ${idf.isOvertime ? `超时 ${idf.overtime}` : ''}`, {
                        fontSize: '26rpx',
                        color: '#333'
                      })
                    ]
                    return arr
                  }),
                  tf.list.labelArr([
                    tf.list.labelArrItem(idf.desc)
                  ], {
                    fontSize: '32rpx',
                    color: '#333',
                    wordBreak: 'break-all',
                    lineHeight: 1.5,
                    whiteSpace: 'pre-wrap',
                    marginTop: '0rpx'
                  }),
                  ...await tool.execFunc(async () => {
                    if (idf.imageList.length) {
                      return [tf.list.imageSelector(idf.imageList, true, 5, () => {}, false)]
                    } else {
                      return []
                    }
                  }),
                  // 隔断
                  ...tf.list.splitArray('0rpx'),
                ]]
              }
              if (subItem.tag == 'review') {
                const idr = subItem
                res = [...res, ...[
                  tf.list.label(`${idr.userData.username} 驳回于 ${idr.createdAt_read}`, {
                    fontSize: '26rpx',
                    color: 'rgb(0,120,215)'
                  }),
                  tf.list.labelArr([
                    tf.list.labelArrItem(idr.desc)
                  ], {
                    fontSize: '32rpx',
                    color: '#333',
                    wordBreak: 'break-all',
                    lineHeight: 1.5,
                    whiteSpace: 'pre-wrap',
                    marginTop: '0rpx'
                  }),
                  // 隔断
                  ...tf.list.splitArray('0rpx'),
                ]]
              }
              if (subItem.tag == 'feedback') {
                const idfb = subItem
                res = [...res, ...[
                  tf.list.label(`${idfb.userData.username} 评价于 ${idfb.createdAt_read}`, {
                    fontSize: '26rpx',
                    color: 'rgb(0,120,215)'
                  }),
                  tf.list.labelArr([
                    tf.list.labelArrItem((() => {
                      if (idfb.rating == 1) return '非常满意'
                      if (idfb.rating == 2) return '满意'
                      if (idfb.rating == 3) return '一般'
                      if (idfb.rating == 4) return '不满意'
                      if (idfb.rating == 5) return '非常不满意'
                    })()),
                    tf.list.labelArrItem(idfb.desc),
                  ], {
                    fontSize: '32rpx',
                    color: '#333',
                    wordBreak: 'break-all',
                    lineHeight: 1.5,
                    whiteSpace: 'pre-wrap',
                    marginTop: '0rpx'
                  }),
                  // 隔断
                  ...tf.list.splitArray('0rpx'),
                ]]
              }
            }

            return res
          })
        ])
      })
    } else {
      tool.handleShowToast(re.content)
    }
  },
  getPhoneList(arr) {
    console.log(arr)
    let t = (() => {
      let re = []
      for (let i = 0; i < arr.length; i++) {
        re.push(arr[i].phone)
      }
      return re
    })()
    t = [...new Set(t)]
    let re = []
    for (let i = 0; i < t.length; i++) {
      for (let i1 = 0; i1 < arr.length; i1++) {
        if (arr[i1].phone == t[i]) {
          re.push(arr[i1])
          break
        }
      }
    }
    return re
  },
  async updateUnreadNum() {
    if (this.isLogined() == false) return
    let re = await tool.requestData('/notification/getUnreadNum', {}, 'get', false)
    if (re.status) {
      store.setItem('unreadNum', re.data)
    } else {

    }
  },
  select: {
    async department(callBack = () => {}) {
      let re = await tool.requestData('/user/getDepartmentList', {}, 'get')
      if (re.status) {
        tool.handleSelect('选择部门', re.data, 'name', (item) => {
          try {
            callBack(item)
          } catch (error) {

          }
          wx.navigateBack()
        })
      } else {
        tool.handleShowToast(re.content, 'error')
      }
    },
    campus(callBack = () => {}) {
      tool.flow(async () => {
        let re_campus = await tool.requestData('/campus/getList', {}, 'get')
        if (!re_campus.status) throw re_campus.content
        tool.handleSelect('选择校区', re_campus.data.default, 'name', (item) => {
          wx.navigateBack()
          try {
            callBack(item)
          } catch (error) {

          }
        })
      }, err => tool.handleShowToast(`${err}`, 'error'))
    },
    category(callBack = () => {}) {
      tool.flow(async () => {
        let re_category = await tool.requestData('/category/getList', {}, 'get')
        if (!re_category.status) throw re_category.content
        tool.handleSelect('选择类别', re_category.data.default, 'name', (item) => {
          wx.navigateBack()
          try {
            callBack(item)
          } catch (error) {

          }
        })
      }, err => tool.handleShowToast(`${err}`, 'error'))
    }
  },
  handleShowActionSheet(arr) {
    let items = []
    for (let i = 0; i < arr.length; i++) items.push(arr[i].name)
    wx.showActionSheet({
      itemList: items,
      success: (e) => {
        e = e.tapIndex
        try {
          arr[e].callBack()
        } catch (error) {

        }
      }
    })
  },
  removeArrDup(arr, key = '') {
    let re = []
    for (let i = 0; i < arr.length; i++) re.push(arr[i][key])
    re = [...new Set(re)]
    for (let i = 0; i < re.length; i++) {
      for (let i1 = 0; i1 < arr.length; i1++) {
        if (arr[i1][key] == re[i]) {
          re[i] = arr[i1]
          break
        }
      }
    }
    return re
  },
  admin: {
    editUserInfo(userId) {
      tool.flow(async () => {
        let re = await tool.requestData('/admin/user/single', {
          id: userId
        })
        if (re.status) {
          let data = re.data
          const refreshData = async () => {
            let re = await tool.requestData('/admin/user/single', {
              id: userId
            })
            if (re.status) {
              data = re.data
            } else {
              throw re.content
            }
          }
          const handleSaveInfo = async (change) => {
            let re = await tool.requestData('/admin/user/saveInfo', {
              id: data.id,
              values: change
            })
            if (re.status) {
              data = Object.assign(data, change)
            } else {
              throw re.content
            }
          }
          tool.controlSettingsPage(`${data.username}`, async (refreshPage_currentUserData) => {
            return [{
                title: '用户信息',
                list: [{
                    title: '用户名',
                    right: {
                      type: 'text',
                      value: data.username,
                    },
                    callBack: async (e) => {
                      tool.controlInput('编辑用户名', '', 'singleText', data.username, async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveInfo({
                            username: value
                          })
                          tool.handleShowToast('成功')
                          await tool.wait(0.5)
                          done()
                          refreshPage_currentUserData()
                        }, err => tool.handleShowToast(`${err}`, 'error'))
                      }, (value) => {
                        if (!value) throw '不能为空'
                        if (value.length > 128) throw '不能长于128'
                      })
                    }
                  },
                  {
                    title: '手机号',
                    right: {
                      type: 'text',
                      value: data.phone,
                    },
                    callBack: async (e) => {
                      tool.controlInput('编辑手机号', '', 'singleText', data.phone, async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveInfo({
                            phone: value
                          })
                          tool.handleShowToast('成功')
                          await tool.wait(0.5)
                          done()
                          refreshPage_currentUserData()
                        }, err => tool.handleShowToast(`${err}`, 'error'))
                      }, (value) => {
                        if (!tool.check.phone(value)) throw '输入正确的手机号'
                      })
                    }
                  },
                  {
                    title: '账号（学号/工号）',
                    right: {
                      type: 'text',
                      value: data.account,
                    },
                    callBack: async (e) => {
                      tool.controlInput('账号（学号/工号）', '', 'singleText', data.account, async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveInfo({
                            account: value
                          })
                          tool.handleShowToast('成功')
                          await tool.wait(0.5)
                          done()
                          refreshPage_currentUserData()
                        }, err => tool.handleShowToast(`${err}`, 'error'))
                      }, (value) => {
                        if (!value) throw '不能为空'
                        if (value.length > 128) throw '不能长于128'
                      })
                    }
                  },
                  {
                    title: '密码',
                    right: {
                      type: 'text',
                      value: data.password,
                    },
                    callBack: async (e) => {
                      tool.controlInput('更换密码', '输入新密码', 'singleText', data.password, async (value, done) => {
                        await tool.flow(async () => {
                          await handleSaveInfo({
                            password: value
                          })
                          tool.handleShowToast('成功')
                          await tool.wait(0.5)
                          done()
                          refreshPage_currentUserData()
                        }, err => tool.handleShowToast(`${err}`, 'error'))
                      }, (value) => {
                        if (!tool.check.password(value)) throw '8到16位且由数字、大小写字母组成'
                      })
                    }
                  },
                  {
                    title: '角色',
                    right: {
                      type: 'text',
                      value: data.role,
                    },
                    callBack: async (e) => {
                      tool.handleShowActionSheet([{
                          name: '老师',
                          callBack: () => tool.flow(async () => {
                            await handleSaveInfo({
                              role: '老师'
                            })
                            tool.handleShowToast('成功')
                            refreshPage_currentUserData()
                          }, err => tool.handleShowToast(`${err}`, 'error'))
                        },
                        {
                          name: '学生',
                          callBack: () => tool.flow(async () => {
                            await handleSaveInfo({
                              role: '学生'
                            })
                            tool.handleShowToast('成功')
                            refreshPage_currentUserData()
                          }, err => tool.handleShowToast(`${err}`, 'error'))
                        },
                      ])
                    }
                  },
                  {
                    title: '解绑微信',
                    right: {
                      type: 'text',
                      value: data.openId ? '已绑定' : '未绑定',
                    },
                    callBack: async (e) => {
                      tool.handleShowModel('解绑微信后此用户需重新登录', true, async () => {
                        await handleSaveInfo({
                          openId: ''
                        })
                        tool.handleShowToast('成功')
                        refreshPage_currentUserData()
                      })
                    }
                  },
                  {
                    title: '状态',
                    right: {
                      type: 'text',
                      value: tool.getUserIsDisabledStatusName(data.isDisabled),
                    },
                    callBack: async (e) => {
                      tool.handleShowActionSheet([{
                          name: '正常登录',
                          callBack: () => tool.flow(async () => {
                            await handleSaveInfo({
                              isDisabled: 0
                            })
                            tool.handleShowToast('成功')
                            refreshPage_currentUserData()
                          }, err => tool.handleShowToast(`${err}`, 'error'))
                        },
                        {
                          name: '禁用',
                          callBack: () => tool.flow(async () => {
                            await handleSaveInfo({
                              isDisabled: 1
                            })
                            tool.handleShowToast('成功')
                            refreshPage_currentUserData()
                          }, err => tool.handleShowToast(`${err}`, 'error'))
                        },
                        {
                          name: '待审核',
                          callBack: () => tool.flow(async () => {
                            await handleSaveInfo({
                              isDisabled: 2
                            })
                            tool.handleShowToast('成功')
                            refreshPage_currentUserData()
                          }, err => tool.handleShowToast(`${err}`, 'error'))
                        },
                      ])
                    }
                  },
                  {
                    title: '部门',
                    right: {
                      type: 'text',
                      value: data.departmentInfo.name,
                    },
                    callBack: async (e) => {
                      tool.select.department(async (e) => {
                        await handleSaveInfo({
                          departmentId: e.id,
                          departmentInfo: e
                        })
                        tool.handleShowToast('成功')
                        refreshPage_currentUserData()
                      })
                    }
                  }
                ]
              },
              {
                title: '负责人权限',
                list: await tool.execFunc(async () => {
                  let re = []
                  for (let i = 0; i < data.permissions.handle.length; i++) re.push({
                    title: `${data.permissions.handle[i].campusInfo.name}-${data.permissions.handle[i].categoryInfo.name}`,
                    callBack: () => tool.handleShowActionSheet([{
                      name: '删除',
                      callBack: () => tool.flow(async () => {
                        await tool.permissions.delete(data.permissions.handle[i].id)
                        await refreshData()
                        refreshPage_currentUserData()
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    }])
                  })
                  re.push({
                    title: '添加',
                    icon: 'add',
                    callBack: () => tool.permissions.handleAdd(userId, 1, () => tool.flow(async () => {
                      await refreshData()
                      refreshPage_currentUserData()
                    }, err => tool.handleShowToast(`${err}`, 'error')))
                  })
                  return re
                })
              },
              {
                title: '审核人权限',
                list: await tool.execFunc(async () => {
                  let re = []
                  for (let i = 0; i < data.permissions.review.length; i++) re.push({
                    title: `${data.permissions.review[i].campusInfo.name}-${data.permissions.review[i].categoryInfo.name}`,
                    callBack: () => tool.handleShowActionSheet([{
                      name: '删除',
                      callBack: () => tool.flow(async () => {
                        await tool.permissions.delete(data.permissions.review[i].id)
                        await refreshData()
                        refreshPage_currentUserData()
                      }, err => tool.handleShowToast(`${err}`, 'error'))
                    }])
                  })
                  re.push({
                    title: '添加',
                    icon: 'add',
                    callBack: () => tool.permissions.handleAdd(userId, 2, () => tool.flow(async () => {
                      await refreshData()
                      refreshPage_currentUserData()
                    }, err => tool.handleShowToast(`${err}`, 'error')))
                  })
                  return re
                })
              },
              {
                title: '管理员权限',
                list: [{
                  title: '管理员',
                  right: {
                    type: 'text',
                    value: data.isAdmin ? '是' : '否',
                  },
                  callBack: async (e) => {
                    tool.handleShowActionSheet([{
                        name: '设为管理员',
                        callBack: () => tool.flow(async () => {
                          await handleSaveInfo({
                            isAdmin: 1
                          })
                          tool.handleShowToast('成功')
                          refreshPage_currentUserData()
                        }, err => tool.handleShowToast(`${err}`, 'error'))
                      },
                      {
                        name: '取消管理员',
                        callBack: () => tool.flow(async () => {
                          await handleSaveInfo({
                            isAdmin: 0
                          })
                          tool.handleShowToast('成功')
                          refreshPage_currentUserData()
                        }, err => tool.handleShowToast(`${err}`, 'error'))
                      }
                    ])
                  }
                }, ]
              },
              {
                title: '查看',
                list: [{
                    title: '此用户新建的巡查',
                    callBack: () => tool.page.searchPatrol({
                      patrolAccount: data.account
                    })
                  },
                  {
                    title: '此用户处理的巡查',
                    callBack: () => tool.page.searchPatrol({
                      handlerAccount: data.account
                    })
                  },
                  {
                    title: '此用户审核的巡查',
                    callBack: () => tool.page.searchPatrol({
                      reviewerAccount: data.account
                    })
                  },
                  {
                    title: '此用户处理巡查评价饼图',
                    callBack: () => tool.handleShowStatisticsPage('patrol_handler', {
                      userId: data.id
                    })
                  },
                  {
                    title: '此用户处理巡查审核情况饼图',
                    callBack: () => tool.handleShowStatisticsPage('patrol_handlerReview', {
                      userId: data.id
                    })
                  },
                  {
                    title: '此用户处理巡查用时情况饼图',
                    callBack: () => tool.handleShowStatisticsPage('patrol_handlerEndTime', {
                      userId: data.id
                    })
                  },
                ]
              }
            ]
          })
        } else {
          throw re.content
        }
      }, err => tool.handleShowToast(`${err}`, 'error'))
    },
    methods: {
      async deleteUsers(arr) {
        let re = await tool.requestData('/admin/user/deleteList', {
          list: arr
        })
        if (re.status) {

        } else {
          throw re.content
        }
      }
    }
  },
  getUserIsDisabledStatusName(n) {
    if (n == 0) return '正常登录'
    if (n == 1) return '禁用'
    if (n == 2) return '待审核'
    return '未知'
  },
  permissions: {
    async add(userId, type, campusId, categoryId) {
      let re = await tool.requestData('/user/permissions/add', {
        userId,
        type,
        campusId,
        categoryId
      })
      if (re.status) {

      } else {
        throw re.content
      }
    },
    async delete(perId) {
      let re = await tool.requestData('/user/permissions/delete', {
        perId
      })
      if (re.status) {

      } else {
        throw re.content
      }
    },
    handleAdd(userId, type, okCallBack = () => {}) {
      const form = {
        categoryId: undefined,
        campusId: undefined,
        categoryName: undefined,
        campusName: undefined,
        userId,
        type
      }
      tool.controlSettingsPage(`添加${type == 1 ? '负责人' : '审核人'}权限`, async (refreshPage_addPer) => {
        let re = [{
            title: '选择校区-类别',
            list: [{
                title: '校区',
                right: {
                  type: 'text',
                  value: form.campusName === undefined ? '未选择' : form.campusName
                },
                callBack: () => tool.select.campus((e) => {
                  form.campusId = e.id
                  form.campusName = e.name
                  refreshPage_addPer()
                })
              },
              {
                title: '类别',
                right: {
                  type: 'text',
                  value: form.categoryName === undefined ? '未选择' : form.categoryName
                },
                callBack: () => tool.select.category((e) => {
                  form.categoryId = e.id
                  form.categoryName = e.name
                  refreshPage_addPer()
                })
              },
            ]
          },
          {
            title: '操作',
            list: [{
              title: '确定',
              callBack: () => tool.flow(async () => {
                await tool.permissions.add(userId, type, form.campusId, form.categoryId)
                tool.handleShowToast('成功')
                try {
                  okCallBack()
                } catch (error) {

                }
                await tool.wait(0.5)
                wx.navigateBack()
              }, err => tool.handleShowToast(`${err}`, 'error'))
            }]
          }
        ]

        return re
      })
    }
  },
  arrDeleteItem(arr, field, value) {
    return arr.filter(item => item[field] != value)
  },
  settings: {
    async set(key, value) {
      let re = await tool.requestData('/setting/set', {
        key,
        value
      })
      if (re.status) {

      } else {
        throw re.content
      }
    }
  },
  async handleUpdateUserData() {
    let re = await tool.requestData('/user/userData', {}, 'get', false)
    if (re.status) {
      store.setItem('userData', re.data)
    } else {

    }
  },
  async handleNotificationItemClick(item) {
    if (item === undefined) {
      tool.handleShowToast('通知不存在', 'error', 800)
      return
    }
    let e = {
      item
    }
    if (e.item.link) {
      let name = e.item.link.name
      let data = e.item.link.data
      if (name == 'openPatrol') {
        tool.page.patrol.info(data)
      }
      if (name == 'downloadFile') {
        wx.setClipboardData({
          data,
          success: async () => {
            await tool.wait(0.1)
            tool.handleShowToast('下载链接已复制到剪切板')
          }
        })

      }
      if (name == 'notifUserList') {
        tool.handleShowNotifUserList(data)
      }
    } else {
      tool.handleShowToast('无操作', 'error')
    }
  },
  async postFrontStatus(content) {
    if (!tool.getHomeData().logFrontStatus) return
    let re = await tool.requestData('/system/logFrontStatus', {
      content
    }, 'post', false)
  },
  handleOpenLocationInWebView(location1, location2) {
    store.setItem('webView', `https://uri.amap.com/marker?position=${location2},${location1}`)
    wx.navigateTo({
      url: '/pages/webView/webView',
    })
  },
  handleShowWebView(url) {
    store.setItem('webView', url)
    wx.navigateTo({
      url: '/pages/webView/webView',
    })
  },
  getDayStartEnd(date) {
    // 将输入的时间转换为Date对象
    let inputDate = new Date(date);

    // 获取该天的开始时间00:00
    let start = new Date(inputDate.setHours(0, 0, 0, 0));

    // 获取该天的结束时间23:59
    let end = new Date(inputDate.setHours(23, 59, 59, 999));

    // 创建返回的对象
    let result = {
      createdStart: this.formatDateTime(new Date(start)),
      createdEnd: this.formatDateTime(new Date(end)),
    };

    return result;
  },
  handleShowStatisticsPage(type = '', data = {}) {
    this.handleShowWebView(config.statisticsURL + '' + this.qsStringify({
      type,
      token: store.getItem('userData').token,
      ...data
    }))
  },
  async handleShowNotifUserList(content) {
    let re = await tool.requestData('/admin/notification/checkList', {
      content
    }, 'get')
    if (re.status) {
      re = re.data
      tool.controlSettingsPage('通知阅读情况', async () => {
        let res = []
        for (let i = 0; i < re.length; i++) {
          res.push({
            title: re[i].userData.username,
            right: {
              type: 'text',
              value: re[i]['是否已读']
            },
            callBack: async () => {
              tool.handleShowActionSheet([{
                  name: `阅读于 ${tool.formatTimeNew(new Date(re[i]['阅读时间']))}`
                },
                {
                  name: '查看用户信息',
                  callBack: () => tool.admin.editUserInfo(re[i]['用户ID'])
                }
              ])
            }
          })
        }

        return [{
          list: res
        }]
      })
    } else {
      tool.handleShowToast(`${re.content}`, 'error')
    }
  },
  feedback: {
    async getMy(date = undefined, openId = undefined) {
      let re = await tool.requestData('/feedback/getUserList', {
        openId: openId ? openId : tool.store.getItem('openId'),
        date
      }, 'get')
      if (re.status) {
        return re.data
      } else {
        throw re.content
      }
    },
    async showDetailPage(id) {
      await tool.flow(async () => {
        let re = await tool.requestData('/feedback/getSingle', {
          id
        }, 'get')
        if (re.status) {
          let data = re.data
          tool.store.setItem('feedBack_detail', data)
          wx.navigateTo({
            url: '/pages/fb_detail/fb_detail',
          })
          return
          tool.controlFormPage('反馈详情', (refreshPage) => {
            const controls = tool.formPageControls
            return tool.formPageControls.main([
                ...(() => {
                  if (data.image) {
                    return [controls.list.imageSelector([data.image], true), ]
                  } else {
                    return []
                  }
                })(),
                controls.list.label(data.content, {
                  fontSize: '48rpx',
                  color: 'black'
                }),
                controls.list.label((data.role === 'student' ? '学生' : '老师') + ' 反馈于 ' + data.createdAt_read, {
                  fontSize: '28rpx'
                }),
                controls.list.label(`校区：${data.campusInfo.name}`, {
                  fontSize: '28rpx'
                }),
                controls.list.label(`类别：${data.categoryInfo.name}`, {
                  fontSize: '28rpx'
                }),
                ...controls.list.conditionItem(data.name,
                  () => controls.list.label(`姓名：${data.name}`, {
                    fontSize: '28rpx'
                  })
                ),
                ...controls.list.conditionItem(data.phone,
                  () => controls.list.label(`手机号：${data.phone}`, {
                    fontSize: '28rpx'
                  })
                ),
                ...controls.list.conditionItem(data.departmentInfo !== undefined,
                  () => controls.list.label(`部门：${data.departmentInfo.name}`, {
                    fontSize: '28rpx'
                  })
                ),
                ...controls.list.conditionItem(data.className,
                  () => controls.list.label(`班级：${data.className}`, {
                    fontSize: '28rpx'
                  })
                ),
                ...(() => {
                  if (data.location1) {
                    return [
                      controls.list.buttonGroup('', [
                        controls.list.button('查看具体位置', () => {
                          wx.openLocation({
                            latitude: parseFloat(data.location1),
                            longitude: parseFloat(data.location2),
                          })
                        })
                      ])
                    ]
                  } else {
                    return []
                  }
                })(),
                controls.list.conditionItem(data.answerContent, () => [
                  controls.list.label(`负责人 ${data.answerUserInfo.name}(${data.answerUserInfo.phone}) 回复：`, {
                    fontSize: '28rpx',
                    color: ' rgb(0,120,215)',
                    fontWeight: 'bold',
                    marginTop: '16rpx'
                  }),
                  controls.list.label(data.answerContent, {
                    fontSize: '48rpx',
                    color: 'black'
                  }),
                  controls.list.label(`回复于 ${data.answerTime_read}`, {
                    fontSize: '28rpx'
                  })
                ])
              ], undefined,
              tool.formPageControls.bottom([
                ...controls.list.conditionItem(data.per.withdraw, () => controls.topBottom.button('撤回', 'delete', () => {
                  tool.feedback.delete(data.id, () => wx.navigateBack())
                }))
              ])
            )
          })
        } else {
          throw re.content
        }
      }, err => wx.showToast({
        title: `${err}`,
        icon: 'error',
        duration: 800
      }))
    },
    delete(id, callBack = () => {}, admin = false) {
      tool.handleShowModel(admin ? '是否删除？' : '是否撤回？', true, () => {
        tool.flow(async () => {
          let re = await tool.requestData((admin ? '/admin' : '') + '/feedback/delete', {
            openId: tool.store.getItem('openId'),
            id: id
          })
          if (re.status) {
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 800
            })
            await tool.wait(0.8)
            tool.store.setItem('feedBack_my_refresh')
            tool.store.setItem('feedBack_deleteItem', id)
            callBack()
          } else {
            throw re.content
          }
        }, err => wx.showToast({
          title: `${err}`,
          icon: 'error',
          duration: 800
        }))
      })
    },
    answer(id, callBack = () => {}) {
      tool.controlInput('输入回复', '', 'multipleText', '', (e) => {
        tool.flow(async () => {
          let re = await tool.requestData('/feedback/update', {
            id,
            content: e,
          })
          if (re.status) {
            tool.store.setItem('feedBack_updateItem', re.data)
            try {
              callBack(re.data)
            } catch (error) {

            }
          } else {
            throw re.content
          }
        }, err => wx.showToast({
          title: `${err}`,
          duration: 800,
          icon: 'error'
        }))
      }, e => {
        if (!e) throw '未输入'
      })
    },
    settings() {
      console.log(wx.getStorageSync('showLogo'))
      tool.controlSettingsPage('设置', () => {
        return [{
            list: [{
              title: '订阅微信服务通知',
              callBack() {
                tool.handleSubWXNotif()
              }
            }]
          },
          ...(() => {
            if (wx.getStorageSync('showLogo') === true) {
              return [{
                list: [{
                  title: '小程序问题反馈',
                  async callBack() {
                    await tool.flow(async () => {
                      let re = await tool.requestData('/chatRoom/chatWithDev', {
                        chatWithDev: true,
                        openId: tool.store.getItem('openId')
                      })
                      if (re.status) {
                        tool.chatRoom.showChatRoomPage(re.data, false)
                      } else {
                        throw re.content
                      }
                    }, err => {
                      tool.handleShowToast(`${err}`, 'error', 800)
                    })
                  }
                }]
              }]
            } else {
              return []
            }
          })()
        ]
      })
    },
    showChatRoomsPage() {
      tool.flow(async () => {
        let re = await tool.requestData('')
      }, err => tool.handleShowToast(`${err}`, 'error', 800))
    },
    showAllOrSearchOptions() {
      tool.handleShowActionSheet([{
          name: '全部',
          callBack() {
            tool.page.searchFeedBack({}, '全部反馈')
            tool.postFrontStatus('点击我的事务 - 管理员管理全部反馈')
          }
        },
        {
          name: '搜索',
          callBack() {
            tool.page.getSearchFeedBackForm(e => {
              tool.page.searchFeedBack(e, '反馈搜索结果')
              tool.postFrontStatus('点击我的事务 - 管理员搜索反馈')
            })
          }
        },
      ])
    }
  },
  async getServerTime() {
    let re = await tool.requestData('/system/getServerTime', {}, 'get')
    if (re.status) {
      return re.data
    } else {
      throw re.content
    }
  },
  handleUpdateProgram() {
    const updateManager = wx.getUpdateManager()

    // 监听检查更新结果
    updateManager.onCheckForUpdate(function (res) {
      console.log('是否有新版本：', res.hasUpdate)
    })

    // 下载新版本成功
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新版本应用并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    // 新版本下载失败
    updateManager.onUpdateFailed(function () {
      wx.showModal({
        title: '更新失败',
        content: '新版本下载失败，请检查网络设置或稍后再试。',
        showCancel: false
      })
    })
  },
  chatRoom: {
    showChatRoomPage(chatRoomId, isHandleUser) {
      tool.flow(async () => {
        let re = await tool.requestData('/chatRoom/getChatHistoryList', {
          openId: tool.store.getItem('openId'),
          chatRoomId,
          isHandleUser
        })
        if (re.status) {
          tool.store.setItem('chatRoomData', {
            data: re.data,
            isHandleUser,
            chatRoomId
          })
          wx.navigateTo({
            url: '/pages/fb_chatRoom/fb_chatRoom',
          })
        } else {
          throw re.content
        }
      }, err => tool.handleShowToast(`${err}`, 'error', 800))
    },
    showChatRoomListPage() {
      tool.flow(async () => {
        let re = await tool.requestData('/chatRoom/getChatRoomList', {
          openId: tool.store.getItem('openId'),
          userId: !tool.store.getItem('userData')?.id ? undefined : tool.store.getItem('userData')?.id
        }, 'get')
        if (re.status) {
          tool.store.setItem('chatRoomListData', re.data)
          wx.navigateTo({
            url: '/pages/fb_chatRooms/fb_chatRooms',
          })
        } else {
          throw re.content
        }
      }, err => tool.handleShowToast(`${err}`, 'error', 800))
    },
    handleWS() {
      ws.on('newChatRoom', (e) => {
        tool.store.setItem('newChatRoom', e)
      })
      ws.on('chatMessage', e => {
        tool.store.setItem('chatMessage', e)
        tool.refreshHomeData()
      })
    },
    async create(openId, feedBackId) {
      await tool.flow(async () => {
        let re = await tool.requestData('/chatRoom/create', {
          feedBackId,
          openId
        })
        if (re.status) {
          tool.chatRoom.showChatRoomPage(re.data, true)
        } else {
          throw re.content
        }
      }, err => {
        tool.handleShowToast(`${err}`, 'error', 800)
      })
    }
  },
  appendChatRoomItem(arr, item) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id === item.id) return arr
    }
    arr.push(item)
    arr.sort((a, b) => {
      return new Date(a.lastChatAt) - new Date(b.lastChatAt)
    })
    for (let i = 0; i < arr.length; i++) delete arr[i].topTitle;
    return this.addTopTitleToArr(arr)
  },
  appendChatRoomMessageItem(arr, item) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id === item.id) return arr
    }
    arr.push(item)
    arr.sort((a, b) => {
      return new Date(a.createdAt) - new Date(b.createdAt)
    })
    for (let i = 0; i < arr.length; i++) delete arr[i].topTitle;
    return this.addTopTitleToArr(arr)
  },
  addTopTitleToArr(re) {
    for (let i = 0; i < re.length; i++) {
      if (!i || this.formatDateString(re[i].createdAt) != this.formatDateString(re[i - 1].createdAt)) {
        re[i].topTitle = this.formatDateString(re[i].createdAt)
      }
    }
    return re
  },
  formatDateString(inputDate) {
    const date = new Date(inputDate);
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const target = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const diffDays = Math.round((target - today) / (1000 * 60 * 60 * 24));

    if (diffDays === 2) return "后天";
    if (diffDays === 1) return "明天";
    if (diffDays === 0) return "今天";
    if (diffDays === -1) return "昨天";
    if (diffDays === -2) return "前天";

    const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const targetWeekday = weekdays[date.getDay()];

    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(today.getDate() - 7);

    const oneWeekLater = new Date();
    oneWeekLater.setDate(today.getDate() + 7);

    // if (target <= oneWeekAgo && target < today) return `上${targetWeekday}`;
    // if (target > today && target <= oneWeekLater) return targetWeekday;

    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    if (year === now.getFullYear()) {
      return `${month}月${day}日`;
    } else {
      return `${year}年${month}月${day}日`;
    }
  },
  decodeURLParamString(url) {
    url = url.split('&')
    let re = {}
    for (let i = 0; i < url.length; i++) {
      url[i] = url[i].split('=')
      re[url[i][0]] = url[i][1]
      try {
        re[url[i][0]] = JSON.parse(re[url[i][0]])
      } catch (error) {

      }
    }
    return re
  },
  async handleOptions(options) {
    let homeData = tool.store.getItem('home')
    await tool.flow(async () => {

      //二维码
      if (options.scene !== undefined) {
        let qrcodeData = decodeURIComponent(options.scene)
        qrcodeData = this.decodeURLParamString(qrcodeData)
        if (qrcodeData.id === 37) {
          wx.navigateTo({
            url: '/pages/fb_add/fb_add',
          })
        } else {
          let re = await tool.requestData('/qrcode/getInfo', {
            openId: tool.store.getItem('openId'),
            qrcodeId: qrcodeData.id
          })
          if (re.status) {

          } else {
            wx.navigateTo({
              url: '/pages/fb_add/fb_add',
            })
            return
          }
          qrcodeData = re.data
          console.log(qrcodeData)
          tool.store.setItem('feedBack_add_autoFill_content', qrcodeData?.data?.content)
          re = await tool.requestData('/feedback/getCampusAndCategory', {
            categoryId: qrcodeData.data.categoryId,
            campusId: qrcodeData.data.campusId
          }, 'get')
          if (re.status) {
            tool.store.setItem('feedBack_add_autoFill_campusCategory', re.data)
          } else {
            throw re.content
          }
          wx.navigateTo({
            url: '/pages/fb_add/fb_add',
          })
        }
      }

      //巡查通知
      if (options.notifId) {
        if (tool.isLogined()) {
          tool.store.setItem('mainCurrentPageIndex', 2)
          let re = await tool.requestData('/notification/getItem', {
            id: options.notifId
          }, 'get', false)
          if (re.status) {
            tool.handleNotificationItemClick(re.data)
          } else {
            tool.handleShowToast(re.content, 'error')
          }
        } else {
          tool.handleNotLogin()
        }
      }

      //巡查系统之外的通知
      if (options.nn) {
        try {
          options.data = JSON.parse(decodeURIComponent(options.data))
        } catch (error) {
          console.log(error)
        }
        if (options.type === 'openFeedBackDetailPage') {
          if (homeData.feedBackData.enable) {
            let id = options.data.id
            id = parseInt(id)
            tool.feedback.showDetailPage(id)
          } else {
            tool.store.setItem('showFeedBack', true)
          }
        }
        if (options.type === 'openMyTasksPage') {
          tool.page.myTasks()
        }
        if (options.type === 'openChatRoomPage') {
          if (homeData.feedBackData.enable) {
            tool.chatRoom.showChatRoomPage(options.data.id, options.data.ishu === 'true')
          } else {
            tool.store.setItem('showFeedBack', true)
          }
        }
      }
    }, err => {
      console.log(err)
      tool.handleShowToast(`${err}`, 'error', 800)
    })
  },
  handleShowFDSelectPage(title, list = [], selectedKey = undefined, callBack = () => {}) {
    store.setItem('fb_select', {
      title,
      list,
      callBack,
      selectedKey
    })
    wx.navigateTo({
      url: '/pages/fb_select/fb_select'
    })
  },
  async handleShowFBMyPage(openId, openIdRead, callBack = () => {}) {
    await tool.flow(async () => {
      let re = await tool.feedback.getMy(undefined, openId)
      tool.store.setItem('feedBack_my', {
        data: re,
        openId: openId,
        openId_read: openIdRead
      })
      wx.navigateTo({
        url: '/pages/fb_my/fb_my',
      })
      try {
        await callBack()
      } catch (error) {

      }
    }, async err => {
      wx.showToast({
        title: `${err}`,
        icon: 'error',
        duration: 800
      })
      try {
        await callBack()
      } catch (error) {

      }
    })
  }
}